我正在尝试使用 ASP.NET C# 将一些数据导出到 CSV。
我使用这段代码:
private void writeCSVfile(DataTable theData, string fileName)
{
StringBuilder dataString = new StringBuilder();
string currentId = Guid.Empty.ToString();
HttpContext context = HttpContext.Current;
context.Response.Clear();
foreach (DataColumn column in GTDSSearchData.Columns)
{
if (column.ColumnName.ToString().ToLower() != "the_id")
{
dataString.Append(column.ColumnName + ",");
}
}
dataString.Remove(dataString.Length - 1, 1);
dataString.Append(Environment.NewLine);
foreach (DataRow row in GTDSSearchData.Rows)
{
currentId = row[1].ToString();
for (int i = 1; i < GTDSSearchData.Columns.Count; i++)
{
dataString.Append(row[i].ToString().Replace(",", string.Empty) + ",");
}
dataString.Remove(dataString.Length - 1, 1);
dataString.Append(Environment.NewLine);
}
context.Response.Write(dataString.ToString());
context.Response.ContentType = "text/csv";
context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName + ".csv");
context.Response.End();
}
我的数据字符串是
test1, 1
"hello world", 10
test2, 2
结果 CSV 文件包含这些内容
test1, 1
hello world, 10
test2, 2
你知道为什么我的双引号消失了,以及在导出到 CSV 文件时如何保留它们。
非常感谢。