我正在尝试为我的CSV编写器写一个标题,但是我收到错误的标题值, 我的代码如下:
定义类:
public class PersonDefinition
{
public string First_Name { get; set; }
}
映射类:
public sealed class PersonDefinitionMap : CsvClassMap<Person>
{
public PersonDefinitionMap()
{
Map(m => m.First_Name).Name("First Name");
}
}
在主程序中:
using (TextWriter writer = new StreamWriter(csvFilePath))
{
var csvWriter = new CsvWriter(writer);
csvWriter.Configuration.Encoding = Encoding.UTF8;
csvWriter.WriteHeader<PersonDefinition>();
}
但输出csv让我得到以下信息:
First_Name
取而代之的是
First Name
(没有空格)
这里的问题在哪里?
答案 0 :(得分:3)
看起来你没有注册映射。
var csvWriter = new CsvWriter(writer);
csvWriter.Configuration.Encoding = Encoding.UTF8;
csvWriter.Configuration.RegisterClassMap<PersonDefinitionMap>(); // <-- here
csvWriter.WriteHeader<PersonDefinition>();
答案 1 :(得分:2)
查看documentation,您需要注册班级地图:
var csv = new CsvReader( textReader );
csv.Configuration.RegisterClassMap<MyClassMap>();
或者在你的情况下:
var csvWriter = new CsvWriter(writer);
csvWriter.Configuration.Encoding = Encoding.UTF8;
csvWriter.Configuration.RegisterClassMap<PersonDefinitionMap>();
csvWriter.WriteHeader<PersonDefinition>();