Showing posts with label Export. Show all posts
Showing posts with label Export. Show all posts

Wednesday, November 10, 2010

How to export DataTable to CSV file


In this short post I will show you how to expert DataTable to CSV file. I have created C# function ExportTableToCsv with one parameted of DataTable data type.

private static string ExportTableToCsv(DataTable sourceTable)
{
    StringBuilder sb = new StringBuilder();

    for (int rowCount = 0; rowCount < sourceTable.Rows.Count; rowCount++)
    {
        for (int colCount = 0; colCount < sourceTable.Columns.Count; colCount++)
        {
            sb.Append(sourceTable.Rows[rowCount][colCount]);
            if (colCount != sourceTable.Columns.Count - 1)
            {
                sb.Append(",");
            }
        }
        if (rowCount != sourceTable.Rows.Count - 1)
        {
            sb.AppendLine();
        }
    }
    return sb.ToString();
}