Created
March 31, 2014 04:33
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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