0

我正在使用 LinqToCSV 将列表输出到 CSV。示例代码片段如下:

class Person
{
    [CsvColumn(Name = "Name", FieldIndex = 1)]
    public string UserName { get; set; }
    [CsvColumn(Name = "Address 1", FieldIndex = 2)]
    public string Address1 { get; set; }
    [CsvColumn(Name = "Telephone", FieldIndex = 3)]
    public string Telephone { get; set; }
}


private void OutputToCSV(string filenamePrefix, List<Person> people)
{
    CsvFileDescription outputFileDescription = new CsvFileDescription
    {
        SeparatorChar = ','
        FirstLineHasColumnNames = true, 
        FileCultureName = "en-GB"
    };

    CsvContext cc = new CsvContext();
    cc.Write(
        people,
        @"C:\temp\people.csv",
        outputFileDescription);            
}

我的问题是电话号码。如果它在对象中为 0123456789012,那么当我在 Excel 中打开 CSV 时,它被视为一个数字,并且前导零被删除。我想将 CSV 中的列预先格式化为文本。

根据停止 Excel 自动将某些文本值转换为日期,我可以用等号开始字段并将值放在引号中,但是我可以设置一个属性,这意味着 LinqToCSV 将为我执行此操作吗?我真的不想使用 LinqToCSV,然后打开文件并编辑它以获得我想要的。

4

3 回答 3

1

您打算创建 CSV 或 Excel 文件吗?如果是后者,那么如果您改用 Nuget 的 Epplus 会不会容易得多?IE:

void Main()
{
  ExcelPackage pck = new ExcelPackage();
  List<Person> people = new List<Person> {
    new Person { UserName="Cetin", Address1="A1", Telephone="012345"},
    new Person { UserName="Timbo", Address1="A2", Telephone="023456"},
    new Person { UserName="StackO", Address1="A3", Telephone="0 345 6789 01 23"},
  };


  var wsEnum = pck.Workbook.Worksheets.Add("MyPeople");

  //Load the collection starting from cell A1...
  wsEnum.Cells["A1"].LoadFromCollection(people, true, TableStyles.Medium9);
  wsEnum.Cells[wsEnum.Dimension.Address].AutoFitColumns();
  //...and save
  var fi = new FileInfo(@"d:\temp\People.xlsx");
  if (fi.Exists)
  {
    fi.Delete();
  }
  pck.SaveAs(fi);
}

class Person
{
  public string UserName { get; set; }
  public string Address1 { get; set; }
  public string Telephone { get; set; }
}
于 2015-11-06T14:20:12.300 回答
0

尝试使用 OutputFormat 来强制它 ToString()。您也可以将它与其他修复程序结合使用并使用 OutputFormat="=C" 但我没有尝试过。

[CsvColumn(Name = "Telephone", FieldIndex = 3, OutputFormat = "C")]
public string Telephone { get; set; }
于 2015-11-06T14:11:00.343 回答
-1

正如您所说,这是一个 Excel 问题,您需要数据具有前导 = 符号,以便 0123456789012 变为 =“0123456789012”。

您可以使用 OutputFormat 更改格式,但您需要使用格式:

[CsvColumn(FieldIndex = 2, OutputFormat = "dd MMM HH:mm:ss")]
于 2015-11-06T14:19:01.280 回答