我正在使用CsvHelper库从一个基本类Person
的IEnumerable<Person>
生成CSV文件。
public class Person
{
public string DisplayName { get; set; }
public int Age { get; set; }
}
我需要编写引用标题,即在生成的文件中,“DisplayName”列应为“Display Name”。
我该如何实现这一要求?
ClassMap
。void Main()
{
using (var stream = new MemoryStream())
using (var writer = new StreamWriter(stream))
using (var reader = new StreamReader(stream))
using (var csv = new CsvWriter(writer))
{
var records = new List<Person>
{
new Test { DisplayName = "one", Age = 1},
new Test { DisplayName = "two", Age = 2 },
};
csv.Configuration.RegisterClassMap<PersonMap>();
csv.WriteRecords(records);
writer.Flush();
stream.Position = 0;
Console.WriteLine(reader.ReadToEnd());
}
}
public class Person
{
public string DisplayName { get; set; }
public int Age { get; set; }
}
public sealed class PersonMap : ClassMap<Person>
{
public PersonMap()
{
Map(m => m.DisplayName).Name("Display Name");
Map(m => m.Age);
}
}
输出:
Display Name,Age
one,1
two,2
我没有头文件,所以我使用了这个快速解决方法:
foreach (var property in typeof(MyCsvClass).GetProperties())
{
csvWriter.WriteField(property.Name.Replace('_', ' '));
}
csvWriter.NextRecord();
csvWriter.WriteRecords(models);
HasHeaderRecord = false
选项。