C# - 写入 CSV 文件时格式化列(单元格格式)

标签 c# .net string

写了导出数据到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/

相关文章:

c# - 异步任务超时

c# - 从 USB 条码扫描仪读取

python - 在python中替换字符串

c# - C# 中的 IPC 机制 - 使用和最佳实践

.net - 对于无效的文件名应该抛出哪个异常?

比较c中的两个相等数组但输出显示不相等

java - 如何从文本文件加载文本并与另一个文本文件进行比较?

c# - .net 根据参数类型选择了错误的调用方法

c# - EmptyDataRow 中的 DropdownList 和 Footer 数据与 SQL 存储过程绑定(bind)

c# - 牛顿软件.Json : error on deserialize objects with generic fields