CsvHelper
CsvHelper copied to clipboard
Change the name of the column (header) when writing to a .csv file during runtime
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?
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; }
}