Column headers in CSV using fileHelpers library?

后端 未结 6 1794
醉话见心
醉话见心 2020-12-23 13:38

Is there a built-in field attribute in the FileHelper library which will add a header row in the final generated CSV?

I have Googled and didn\'t find much info on it

6条回答
  •  余生分开走
    2020-12-23 14:03

    Just to include a more complete example, which would have saved me some time, for version 3.4.1 of the FileHelpers NuGet package....

    Given

    [DelimitedRecord(",")]
    public class Person
    {
       [FieldCaption("First")]
       public string FirstName { get; set; }
    
       [FieldCaption("Last")]
       public string LastName { get; set; }
    
       public int Age { get; set; }
    }
    

    and this code to create it

    static void Main(string[] args)
    {
        var people = new List();
        people.Add(new Person() { FirstName = "James", LastName = "Bond", Age = 38 });
        people.Add(new Person() { FirstName = "George", LastName = "Washington", Age = 43 });
        people.Add(new Person() { FirstName = "Robert", LastName = "Redford", Age = 28 });
    
        CreatePeopleFile(people);
    }
    
    private static void CreatePeopleFile(List people)
    {
        var engine = new FileHelperEngine();
    
        using (var fs = File.Create(@"c:\temp\people.csv"))
        using (var sw = new StreamWriter(fs))
        {
            engine.HeaderText = engine.GetFileHeader();
            engine.WriteStream(sw, people);
            sw.Flush();
        }
    }
    

    You get this

    First,Last,Age
    James,Bond,38
    George,Washington,43
    Robert,Redford,28
    

提交回复
热议问题