Export DataTable to CSV quick and dirty:
static void DataTableToCSV(string path, DataTable table, bool isFirstRowHeader)
{
var lines = new List<string>();
if (isFirstRowHeader)
{
string[] colnames = table.Columns.Cast<DataColumn>().Select(column => column.ColumnName.Replace(",","")).ToArray();
var header = string.Join(",", colnames);
lines.Add(header);
}
var valueLines = table.AsEnumerable()
.Cast<DataRow>()
.Select(row => string.Join(",",
row.ItemArray
.Select(o => "\"" + o.ToString().Replace(",","") + "\"")
.ToArray()));
var allLines = string.Join(Environment.NewLine, valueLines.ToArray<string>());
lines.Add(allLines);
File.WriteAllLines(path, lines.ToArray());
}
No comments:
Post a Comment