Search code examples
c#csvfilehelpers

Column headers in CSV using fileHelpers library?


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. Currently I have this:

DelimitedFileEngine _engine = new DelimitedFileEngine(T);
_engine.WriteStream
        (HttpContext.Current.Response.Output, dataSource, int.MaxValue);

It works, but without a header.

I'm thinking of having an attribute like FieldTitleAttribute and using this as a column header.

So, my question is at which point do I check the attribute and insert header columns? Has anyone done something similar before?

I would like to get the headers inserted and use custom text different from the actual field name just by having an attribute on each member of the object:

[FieldTitleAttribute("Custom Title")]
private string Name

and maybe an option to tell the engine to insert the header when it's generated.

So when WriteStream or WriteString is called, the header row will be inserted with custom titles.

I have found a couple of Events for DelimitedFileEngine, but not what's the best way to detect if the current record is the first row and how to insert a row before this.


Solution

  • 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?