Column headers in CSV using fileHelpers library?

后端 未结 6 1750
醉话见心
醉话见心 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 13:58

    Here's some code that'll do it: https://gist.github.com/1391429

    To use it, you must decorate your fields with [FieldOrder] (a good FileHelpers practice anyway). Usage:

    [DelimitedRecord(","), IgnoreFirst(1)]
    public class Person
    {
        // Must specify FieldOrder too
        [FieldOrder(1), FieldTitle("Name")]
        string name;
    
        [FieldOrder(2), FieldTitle("Age")]
        int age;
    }
    
    ...
    
    var engine = new FileHelperEngine<Person>
    {
        HeaderText = typeof(Person).GetCsvHeader()
    };
    
    ...
    
    engine.WriteFile(@"C:\people.csv", people);
    

    But support for this really needs to be added within FileHelpers itself. I can think of a few design questions off the top of my head that would need answering before it could be implemented:

    • What happens when reading a file? Afaik FileHelpers is currently all based on ordinal column position and ignores column names... but if we now have [FieldHeader] attributes everywhere then should we also try matching properties with column names in the file? Should you throw an exception if they don't match? What happens if the ordinal position doesn't agree with the column name?
    • When reading as a data table, should you use A) the field name (current design), or B) the source file column name, or C) the FieldTitle attribute?
    0 讨论(0)
  • 2020-12-23 14:00

    I don't know if you still need this, but here is the way FileHelper is working : To include headers of columns, you need to define a string with headers delimited the same way as your file. For example with '|' as delimiter :

     public const string HeaderLine = @"COLUMN1|COLUMN2|COLUMN3|...";
    

    Then, when calling your engine :

    DelimitedFileEngine _engine = new DelimitedFileEngine<T> { HeaderText = HeaderLine };
    

    If you don't want to write the headers, just don't set the HeaderText attribute on the engine.

    0 讨论(0)
  • 2020-12-23 14:01

    I found that you can use the FileHelperAsyncEngine to accomplish this. Assuming your data is a list called "output" of type "outputData", then you can write code that looks like this:

            FileHelperAsyncEngine outEngine = new FileHelperAsyncEngine(typeof(outputData));
            outEngine.HeaderText = "Header1, Header2, Header3";
            outEngine.BeginWriteFile(outputfile);
            foreach (outputData line in output){
                outEngine.WriteNext(line);
            }
            outEngine.Close();
    
    0 讨论(0)
  • 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<Person>();
        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<Person> people)
    {
        var engine = new FileHelperEngine<Person>();
    
        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
    
    0 讨论(0)
  • 2020-12-23 14:20
    List<MyClass> myList = new List<MyClass>();
    FileHelperEngine engine = new FileHelperEngine(typeof(MyClass));
    String[] fieldNames = Array.ConvertAll<FieldInfo, String>(typeof(MyClass).GetFields(), delegate(FieldInfo fo) { return fo.Name; });
    engine.HeaderText = String.Join(";", fieldNames);
    engine.WriteFile(MapPath("MyClass.csv"), myList);
    
    0 讨论(0)
  • 2020-12-23 14:25

    I know this is an old question, but here is an answer that works for v2.9.9

    FileHelperEngine<Person> engine = new FileHelperEngine<Person>();
    engine.HeaderText = engine.GetFileHeader();
    
    0 讨论(0)
提交回复
热议问题