C# : Write DataTable To CSV

Here’s a quick code to write data from database to a CSV format file in C# .NET.

I find this function really useful as I frequently come across this scenario where I have to create a report for the client.

Once our data is loaded into a DataTable, this function can be used.


public static string ToCsv(DataTable table)
{
var result = new StringBuilder();
for (int i = 0; i < table.Columns.Count; i++)
{
result.Append(table.Columns[i].ColumnName);
result.Append(i == table.Columns.Count - 1 ? "\n" : ",");
}

foreach (DataRow row in table.Rows)
{
for (int i = 0; i < table.Columns.Count; i++)
{
result.Append("'"+row[i].ToString());
result.Append(i == table.Columns.Count - 1 ? "\n" : ",");
}
}

return result.ToString();
}

The first “foreach” loop creates table headers and the second loop writes data from rows.

Hope this will be useful to you as well 🙂

 

Tags: