【问题标题】:Create CSV from String Array C# [duplicate]从字符串数组 C# 创建 CSV [重复]
【发布时间】:2018-07-19 14:39:48
【问题描述】:

我想创建一个 CSV,但是当一个值有逗号时,它的格式会错误。

List<string[]> output = new List<string[]>();
output.Add(valuesRow.ToArray());
int length = output.Count;
for (int index = 0; index < length; index++)
{
 stringBuilder.AppendLine(string.Join(delimiter,output[index]));
}

但是当output[index] 具有逗号的值时,它的格式会错误。

【问题讨论】:

  • 你能把output[index]的逗号去掉吗?

标签: c# export-to-csv comma


【解决方案1】:

改变

stringBuilder.AppendLine(string.Join(delimiter,output[index]));

到

stringBuilder.AppendLine(string.Join(delimiter,output[index].Select(x=>"\"" + x + "\"")));

【讨论】:

  • 当然,下一个问题是处理包含双引号字符的字段。
  • @JoelCoehoorn 当然 :) x.Replace("\"","\"\"");
【解决方案2】:

您可以使用 CsvHelper 生成 .csv 输出。您可以指定列并通过字段名称注入您的值。

https://joshclose.github.io/CsvHelper/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-05
    • 2014-10-24
    • 2015-01-22
    • 1970-01-01
    • 2016-08-10
    • 1970-01-01
    相关资源
    最近更新 更多