DataTable 导出 CSV,支持.NET Framework 4.0以上。
public byte[] DataTableToCSV(DataTable data)
{
StringBuilder sb = new StringBuilder();
IEnumerable<string> columnNames = data.Columns.Cast<DataColumn>().
Select(column => column.ColumnName);
sb.AppendLine(string.Join(",", columnNames));
foreach (DataRow row in data.Rows)
{
IEnumerable<string> fields = row.ItemArray.Select(field =>
string.Concat("\"", field.ToString().Replace("\"", "\"\""), "\""));
sb.AppendLine(string.Join(",", fields));
}
return System.Text.Encoding.Default.GetBytes(sb.ToString());
}