CsvHelper : Adding a title using CsvHelper

后端 未结 3 2035
醉酒成梦
醉酒成梦 2021-01-15 09:46

I am using CsvHelper to convert dapper objects to CsvFiles. I am using classmaps to map properties for indices and name mapping. The issue is I need a row with the t

3条回答
  •  梦毁少年i
    2021-01-15 10:32

    For CSVHelper version 15.0.0 and above use:

    void Main()
    {
        var records = new List
        {
            new Foo { Id = 1, Name = "one" },
            new Foo { Id = 2, Name = "two" },
        };
        using (var writer = new StringWriter())
        using (var csv = new CsvWriter(writer, CultureInfo.CurrentCulture))
        {
            csv.Configuration.RegisterClassMap();
    
            csv.WriteField("Title:");
            csv.WriteField("Title");
            csv.NextRecord();
    
            csv.WriteRecords(records);
            writer.ToString().Dump();
        }
    }
    
    public class Foo
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    
    public class FooMap : ClassMap
    {
        public FooMap()
        {
            Map(m => m.Id).Index(0).Name("S.No.");
            Map(m => m.Name).Index(1);
        }
    }
    

提交回复
热议问题