Search code examples
c#excelcsvfluentcsvhelper

How do I configure CsvHelper to always quote a specific field in its CSV output?


I am using the CsvHelper package to write my C# models to Csv. I am using fluent class maps (inheriting from CsvClassMap) to define my field to property mappings.

The issue I have is that some of the property values look like dates to excel. For example "2 - 4". I expect the end user to use excel to view these CSV's. I do not want these values to show as dates, so I am looking to have CsvHelper surround this field by quotes. However, I want ONLY this field surrounded by quotes. There are OTHER fields containing data I WANT to be interpreted (e.g. dates). Can I configure my mapping to specify this field should be quoted? I've played with using a type converter, but that's clearly the wrong approach because this is converting the VALUE and not instructing how to format the field.


Solution

  • As of version 12 you can do this:

    const int indexToQuote = 4;
    csv.Configuration.ShouldQuote = (field, context) => 
        context.Record.Count == indexToQuote && 
        context.HasHeaderBeenWritten;