CsvHelper icon indicating copy to clipboard operation
CsvHelper copied to clipboard

Change the name of the column (header) when writing to a .csv file during runtime

Open dklein9500 opened this issue 4 years ago • 1 comments

How can I change name of the column when writing to the file during the runtime?

I've only found out that you can change the name in the class with the attribute [Name("NewColumnName")], but this only works if I know beforehand how the column should be named.

I already know the amount of properties and just want to name them differently in the csv. Using a dynamic object for that seems to be elaborate.

Is there another way, that I just haven't found yet?

dklein9500 avatar Oct 26 '21 14:10 dklein9500

Write the header manually, then write all the records.

void Main()
{
    var records = new List<Foo>
    {
        new Foo { Id = 1, Name = "one" },
    };
    var config = new CsvConfiguration(CultureInfo.InvariantCulture)
    {
    };
    using (var writer = new StringWriter())
    using (var csv = new CsvWriter(writer, config))
    {
        csv.WriteField("ID");
        csv.WriteField("NAME");
        csv.NextRecord();
        foreach (var record in records)
        {
            csv.WriteRecord(record);
            csv.NextRecord();
        }
        writer.Dump();
    }
}

private class Foo
{
    public int Id { get; set; }
    public string Name { get; set; }
}

JoshClose avatar Oct 26 '21 15:10 JoshClose