【发布时间】: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”。