我正在使用CsvHelper将dapper对象转换为CsvFiles。我使用classmaps来映射属性到索引和名称。问题是,在记录被写入之前,我需要一个带有表格标题的行,如下所述:
我的旧代码没有标题:
using (var writer = new StreamWriter(@"C:\Users\NPandian\Desktop\test.csv", false, System.Text.Encoding.UTF8))
using (var csvWriter = new CsvWriter(writer))
{
var ReportName = "Test Class";
csvWriter.Configuration.RegisterClassMap(classMap);
csvWriter.WriteRecords(records);
writer.Close();
}
旧的 Csv 文件:
我的当前代码解决方案:
using (var writer = new StringWriter())
using (var csvWriter = new CsvWriter(writer))
{
var ReportName = "Test Class";
csvWriter.Configuration.RegisterClassMap(classMap);
csvWriter.WriteRecords(records);
writer.Close();
return $"ReportName:, {ReportName},\n{csvWriter.Context.Writer.ToString()}";
}
我的问题: 1)CsvHelper能否实现? 2)如果可以,如何实现?
csvWriter.WriteRecords
之前,您可以直接向StreamWriter中写入,例如使用writer.WriteLine("Title : {0}",someText);
。 - Panagiotis Kanavos