Skip to content

Instantly share code, notes, and snippets.

@superlucky8848
Created March 31, 2014 04:33
Show Gist options
  • Save superlucky8848/9885375 to your computer and use it in GitHub Desktop.
Save superlucky8848/9885375 to your computer and use it in GitHub Desktop.
A easy piece of code for C# to convert DataTable to CSV for Excel import.
public static bool DataTableToCSV(DataTable dtSource, StreamWriter writer, bool includeHeader)
{
if (dtSource == null || writer == null) return false;
if (includeHeader)
{
string[] columnNames = dtSource.Columns.Cast<DataColumn>().Select(column => "\"" + column.ColumnName.Replace("\"", "\"\"") + "\"").ToArray<string>();
writer.WriteLine(String.Join(",", columnNames));
writer.Flush();
}
foreach (DataRow row in dtSource.Rows)
{
string[] fields = row.ItemArray.Select(field => "\"" + field.ToString().Replace("\"", "\"\"") + "\"").ToArray<string>();
writer.WriteLine(String.Join(",", fields));
writer.Flush();
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment