代码之家  ›  专栏  ›  技术社区  ›  StepUp

从对象列表创建包含多个列的CSV

  •  0
  • StepUp  · 技术社区  · 7 年前

    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 回复  |  直到 7 年前
        1
  •  3
  •   Ashkan Mobayen Khiabani    7 年前

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

    sep=,
    

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