列值转换为公式/指数

问题描述

在写入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; }
}

非常感谢您!

解决方法

只需添加一组双引号即可。 CsvHelper自动使用另一组双引号对字符串中的引号进行转义。字符串=""747313016112""将以=""""747313016112""""结尾,因为CsvHelper将转义每个双引号。这就是为什么您的值在Excel中看起来像"747313016112"的原因。

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

CsvHelper正在关注RFC 4180

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

例如:

“ aaa”,“ b”,“ bb”,“ ccc”

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...