使用 CsvHelper 控制 header 字段名称
Control header field names with CsvHelper
在使用 CsvHelper 6.1.0 写入 CSV 文件时,文档仅一次提到在写入时控制 header 名称:
"When writing, only the first name is used."
我的代码符合给定的示例:
Map(m => m.ReportingGroup).Name("Reporting Group");
Map(m => m.Merchant);
Map(m => m.ActivityDate).Name("Activity Date");
Map(m => m.SettlementDate).Name("Settlement Date");
写操作时没有写空格!
ReportingGroup,Merchant,ActivityDate,SettlementDate
我的 Read() 和 Write(),如果需要:
public static IEnumerable<TR> Read<TR, TMap>(string filename)
where TMap : ClassMap
{
List<TR> records;
using (var sr = new StreamReader(filename))
{
var csv = new CsvReader(sr);
csv.Configuration.RegisterClassMap<TMap>();
records = csv.GetRecords<TR>().ToList();
}
return records;
}
public static void Write<T>(IEnumerable<T> records, string filename, Logger logger)
{
var enumerable = records as IList<T> ?? records.ToList();
logger?.Debug($"Writing {enumerable.Count} records to file: {filename}");
using (var fcreate = File.Open(filename, FileMode.Create))
using (var writer = new StreamWriter(fcreate))
{
var csv = new CsvWriter(writer);
csv.WriteRecords(enumerable);
}
logger?.Debug("Writing complete.");
}
您在写作时需要注册您的class地图。看的时候好像有,写的时候好像没有。
在使用 CsvHelper 6.1.0 写入 CSV 文件时,文档仅一次提到在写入时控制 header 名称:
"When writing, only the first name is used."
我的代码符合给定的示例:
Map(m => m.ReportingGroup).Name("Reporting Group");
Map(m => m.Merchant);
Map(m => m.ActivityDate).Name("Activity Date");
Map(m => m.SettlementDate).Name("Settlement Date");
写操作时没有写空格!
ReportingGroup,Merchant,ActivityDate,SettlementDate
我的 Read() 和 Write(),如果需要:
public static IEnumerable<TR> Read<TR, TMap>(string filename)
where TMap : ClassMap
{
List<TR> records;
using (var sr = new StreamReader(filename))
{
var csv = new CsvReader(sr);
csv.Configuration.RegisterClassMap<TMap>();
records = csv.GetRecords<TR>().ToList();
}
return records;
}
public static void Write<T>(IEnumerable<T> records, string filename, Logger logger)
{
var enumerable = records as IList<T> ?? records.ToList();
logger?.Debug($"Writing {enumerable.Count} records to file: {filename}");
using (var fcreate = File.Open(filename, FileMode.Create))
using (var writer = new StreamWriter(fcreate))
{
var csv = new CsvWriter(writer);
csv.WriteRecords(enumerable);
}
logger?.Debug("Writing complete.");
}
您在写作时需要注册您的class地图。看的时候好像有,写的时候好像没有。