写了导出数据到csv文件的方法。
如果单元格的值在 csv 中具有 DEC20
,则为 20-Dec
,这是不正确的。
我的代码是这样的:
for (int i = 0; i < myData.Count(); i++)
{
sb.AppendLine(string.Join(delimiter,
Common.FormatExportString(myData[i].Code),
Common.FormatExportString(myData[i].Name),
Common.FormatExportString(myData[i].Description)));
}
//returns the file after writing the stream to the csv file.
return File(new System.Text.UTF8Encoding().GetBytes(sb.ToString()), "text/csv", fileName);
请帮助我使用 C# 获取要在 excel (csv) 文件中显示的确切 string
格式。
例如: myData[i].Name 数据将是
DEC20, or 2-5
像这样,
但 csv(excel) 中的输出显示为
20-Dec and 5-May
而不是原来的。
最佳答案
问题不在于 csv 导出,如果您用记事本打开 csv 文件,它的格式是正确的。 Excel 会自动检测单元格类型作为日期并将其显示为日期。
为避免这种行为,将文本用引号括起来并在其前面放置一个 =
,如下所示:
= "DEC20"
文件应该变成
= "field1", = "field2", = "field...", = "DEC20", ...
你的方法应该变成:
for (int i = 0; i < myData.Count(); i++)
{
sb.AppendLine(string.Join(delimiter,
" = \"",
Common.FormatExportString(myData[i].Code),
Common.FormatExportString(myData[i].Name),
Common.FormatExportString(myData[i].Description)
"\""));
}
//returns the file after writing the stream to the csv file.
return File(new System.Text.UTF8Encoding().GetBytes(sb.ToString()), "text/csv", fileName);
关于C# - 写入 CSV 文件时格式化列(单元格格式),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14254375/