Column headers in CSV using fileHelpers library?

后端 未结 6 1781
醉话见心
醉话见心 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
    {
        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?

提交回复
热议问题