我正在使用joshclose的Csv Helper来编写csv文件。我使用了类映射。根据文档,我不需要在类映射中显式地忽略未使用的属性,因为csv helper将仅使用映射中提到的属性,但这不会发生。这是代码。
public sealed class ExportInvoicesCsvMap : CsvClassMap<Invoice>
{
public ExportInvoicesCsvMap()
{
Map(i => i.Number).Index(0).Name("Number");
Map(i => i.SupplierName).Index(1).Name("Supplier Name");
}
}
这是我注册类映射的地方。
List<Invoice> result = _invoiceService.GetInvoices().ToList();// Getting 300 records
var config = new CsvConfiguration();
config.RegisterClassMap<ExportInvoicesCsvMap>();
_csvWriter = new CsvWriter(new CsvFileWriter(_fullPath), config);
_csvWriter.WriteRecords(result);
_csvWriter.Dispose();
但我仍然在csv中获得整个发票模型数据。
答案 0 :(得分:0)
CsvHelper在不忽略属性的情况下进行修正。你可能会遗漏一些东西。请查看以下代码。
public class Invoice
{
public int Number { get; set; }
public string SupplierName { get; set; }
public int Amount { get; set; }
}
public sealed class ExportInvoicesCsvMap : CsvClassMap<Invoice>
{
public ExportInvoicesCsvMap()
{
Map(i => i.Number).Index(0).Name("Number");
Map(i => i.SupplierName).Index(1).Name("Supplier Name");
}
}
var config = new CsvConfiguration();
config.RegisterClassMap<ExportInvoicesCsvMap>();
List<Invoice> list = new List<Invoice>();
list.Add(new Invoice
{
Number = 1,
SupplierName = "SN",
Amount=7
});
using (var sw = new StreamWriter(@"test.csv"))
{
var _csvWriter = new CsvWriter(sw, config);
IEnumerable records = list;
_csvWriter.WriteRecords(records);
}