JuChom
JuChom

Reputation: 5989

Custom header format with CSVHelper

I need to write a CSV file with headers in camel case.

Imagine we have this class

public class Person
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

And the following code

public void Main()
{
    var p = new Person { Id = 1, FirstName = "John", LastName = "Doe" };
    
    using (var writer = new StringWriter())
    using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture, true))
    {
        csv.WriteHeader<Person>();
        csv.NextRecord();
        csv.WriteRecord(p);
        csv.Flush();
        var newRecord = writer.ToString();
        newRecord.Dump();
    }
}

This will output the following

Id,FirstName,LastName
1,John,Doe

I would like the header to be camel case formatted

id,firstName,lastName
1,John,Doe

Last important thing is, I don't know the objects so ClassMaps or attributes are not an options.

Is there a way to configure how the header are formatted with CSVHelper ?

Upvotes: 1

Views: 4262

Answers (1)

David Specht
David Specht

Reputation: 9044

Using DefaultClassMap<T> this should work for any class you provide.

public void Main()
{
    var p = new Person { Id = 1, FirstName = "John", LastName = "Doe" };
    
    using (var writer = new StringWriter())
    using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture, true))
    {
        var map = new DefaultClassMap<Person>();
        
        map.AutoMap(CultureInfo.InvariantCulture);
        
        foreach (var memberMap in map.MemberMaps)
        {
            memberMap.Data.Names.Add(System.Text.Json.JsonNamingPolicy.CamelCase.ConvertName(memberMap.Data.Member.Name));
        }
        
        csv.Context.RegisterClassMap(map);
        
        csv.WriteHeader<Person>();
        csv.NextRecord();
        csv.WriteRecord(p);
        csv.Flush();
        var newRecord = writer.ToString();
        newRecord.Dump();
    }
}

public class Person
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Upvotes: 3

Related Questions