通过对象列表创建包含许多列的CSV文件

时间:2019-03-15 20:25:20

标签: c# csv generics

我正在尝试使用the following code to generate CSV file

public static IEnumerable<string> ToCsv<T>(IEnumerable<T> objectlist
    , string separator = ",", bool header = true)
{
    FieldInfo[] fields = typeof(T).GetFields();
    PropertyInfo[] properties = typeof(T).GetProperties();
    if (header)
    {
        yield return String.Join(separator, fields                
                .Select(f => f.Name)
                .Concat(properties.Select(p => p.Name))
                .ToArray()); 
    }
    foreach (var o in objectlist)
    {
        yield return string.Join(separator, fields
            .Select(f=>(f.GetValue(o) ?? "")
            .ToString())
            .Concat(properties
            .Select(p=>(p.GetValue(o,null) ?? "").ToString())).ToArray());
    }
}

并生成CSV文件:

public class Person
{
    public int IdPerson { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

var persons = new List<Person>
{
    new Person(){IdPerson=1, FirstName = "FirstName, 1", LastName = "LastName 1" },
    new Person(){IdPerson=2, FirstName = "FirstName/ 2", LastName = "LastName 2" },
    new Person(){IdPerson=3, FirstName = "FirstName 3", LastName = "LastName 3" },
};

using (TextWriter tw = File.CreateText(@"D:\testoutput.csv"))
{
   foreach (var line in ExcelExport.ToCsv(persons))
   {
       tw.WriteLine(line);
   }                
}

但是,我所有的数据都嵌套在一列中:

enter image description here

如何将以上数据放在不同的列中?

1 个答案:

答案 0 :(得分:3)

csv没什么问题,只是excel无法将逗号识别为分隔符。将此行添加为csv文件的第一行:

sep=,

它将正常工作。

此外,请注意,您必须将每个项目都用双引号引起来,以转义其中的逗号,并用2个双引号替换任何双引号(文本内部),以在文本中对双引号进行换行:

yield return String.Join(separator, 
            fields.Select(f => $"\"{f.Name.Replace("\"","\"\"")}\"")
            .Concat(properties.Select(p=>p.Name)).ToArray());