我采用了一些将 DataTable 转换为 CSV 文件的代码。它似乎运作良好,除非在实际数据中使用逗号。在这种情况下有没有办法显示逗号?这就是我所做的:
StringBuilder sb = new StringBuilder();
IEnumerable<string> columnNames = dtResults.Columns
.Cast<DataColumn>()
.Select(column => column.ColumnName);
sb.AppendLine(string.Join(",", columnNames));
foreach (DataRow row in dtResults.Rows)
{
IEnumerable<string> fields = row.ItemArray.Select(field => field.ToString());
sb.AppendLine(string.Join(",", fields));
}
File.WriteAllText(saveFileDialog.FileName, sb.ToString());