【问题标题】:Column value is converted to formula/exponent列值转换为公式/指数
【发布时间】:2020-09-01 15:01:15
【问题描述】:

在编写 CSV 文件时,我在处理特定数据列时遇到了一些问题。大多数情况下,该值超过 11 个字符/数字。所以它在 CSV 中生成为7.47313E+11,而它实际上应该读为747313016112。我最初使用this answered question 作为参考来尝试解决我的问题,但它不起作用。

需要注意的一点是数据库中的列(标题为Barcode)是一个varchar。但是,只有数字值会保存到此列。所以我猜在 CSV 生成过程中(或生成之后)的某个时刻,Excel 会将其识别为数字,而不是字符串。

到目前为止,这是我的工作代码:

public static void GenerateChartsCSVFile(IEnumerable<ChartsData> chartsData)
{
    string fullPath = "C:\\chart-data.csv";

    using (var writer = new StreamWriter(fullPath, true, Encoding.GetEncoding("iso-8859-1")))
    using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
    {
        csv.WriteRecords(chartsData);

        writer.Flush();
    }

    if (File.Exists(fullPath))
        Console.WriteLine("Charts CSV file " + csvFile + " successfully created!");
    else
        Console.WriteLine("Oops, something went wrong with generating the Charts CSV file.");
}

数据模型:

public class ChartsData
{
    public string CatalogueID { get; set; }
    public string Barcode { get; set; }
    public string Title { get; set; }
    public string ReleaseDate { get; set; }
    public int DiscNo { get; set; }
    public int TrackNo { get; set; }
    public string TrackTitle { get; set; }
    public string ISRC { get; set; }
    public string Duration { get; set; }
    public string LabelID { get; set; }
    public string Label { get; set; }
    public string TrackContributors { get; set; }
}

非常感谢您!

【问题讨论】:

  • 使用记事本(而不是 Excel)打开 csv 文件,您的条码是否仍以指数形式显示?
  • 对不起,我的意思是说我确实尝试过。是的,当我在记事本中打开文件时,条形码的值是完美的。该问题仅存在于 Excel 中。
  • @JohnWu 我试过这样做,但 Excel 现在将额外的双引号集识别为字符串的一部分。所以现在每个条形码单元格中的值看起来像“747313016112”。

标签: c# csvhelper


【解决方案1】:

只需添加一组双引号。 CsvHelper 使用另一组双引号自动转义字符串中的引号。字符串=""747313016112"" 最终将成为=""""747313016112"""",因为CsvHelper 将转义每个双引号。这就是为什么您的值在 Excel 中看起来像 "747313016112"

chartsData.Barcode = "=\"" + chartsData.Barcode + "\"";

CsvHelper 正在关注RFC 4180

  1. 如果使用双引号将字段括起来,则使用双引号 出现在字段内必须通过在它前面加上 另一个双引号。

例如:

"aaa","b""bb","ccc"

【讨论】:

    猜你喜欢
    • 2021-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-09
    • 2016-08-09
    相关资源
    最近更新 更多