Skip to main content
 首页 » 编程设计

c#之使用 csv helper 将集合的集合写入 csv 文件

2024年01月13日34lori

我正在使用 csvhelper 将数据写入 csv 文件。我正在使用 C# 和 VS2010。我想写的对象是一个类型为 Dictionary< long,List<HistoricalProfile>> 的复杂数据类型对象

下面是我用来将数据写入 csv 文件的代码:

Dictionary<long, List<HistoricalProfile>> profiles  
    = historicalDataGateway.GetAllProfiles();  
 
var fileName = CSVFileName + ".csv"; 
CsvWriter writer = new CsvWriter(new StreamWriter(fileName)); 
 
foreach (var items in profiles.Values)     
{ 
    writer.WriteRecords(items); 
} 
 
writer.Dispose(); 

第二次循环时报错

The header record has already been written. You can't write it more than once.

你能告诉我我做错了什么吗?我的最终目标是拥有一个包含大量记录的单个 csv 文件。

提前致谢!

请您参考如下方法:

你见过这个图书馆吗http://www.filehelpers.net/这使得读取和写入 CSV 文件变得非常容易

那么你的代码就是

var profiles = historicalDataGateway.GetAllProfiles();  // should return a list of HistoricalProfile 
var engine = new FileHelperEngine<HistoricalProfile>(); 
// To Write Use: 
engine.WriteFile("FileOut.txt", res);