【问题标题】:CSVHelper - Possible to Write List of DictionaryCSVHelper - 可以写字典列表
【发布时间】:2020-08-29 18:02:18
【问题描述】:

我有一个具有相同键列表但值不同的字典列表。有没有办法使用 CSVHelper 将其写入 CSV 文件?我有下面的示例代码,但显然它不起作用。

       static void Main(string[] args)
        {

            List<Dictionary<String, String>> records = new List<Dictionary<string, string>>();
            Dictionary<String, String> data1 = new Dictionary<String, String>();
            data1.Add("Name1", "Value1");
            data1.Add("Name2", "Value2");
            records.Add(data1);

            Dictionary<String, String> data2 = new Dictionary<String, String>();
            data2.Add("Name1", "Value1");
            data2.Add("Name2", "Value2");
            records.Add(data2);

            using (var writer = new StreamWriter("e:\\temp\\test.csv"))
            using (var csv = new CsvWriter(writer))
            {

                csv.WriteRecords(records);
//GEtting exception here
//CsvHelper.Configuration.CsvConfigurationException: 'Types that inherit IEnumerable cannot be auto mapped. Did you accidentally call GetRecord or WriteRecord which acts on a single record instead of calling GetRecords or WriteRecords which acts on a list of records?'

            }
        }

有什么办法吗?

谢谢!

【问题讨论】:

    标签: c# csvhelper


    【解决方案1】:

    我相信唯一的办法就是手写。

    using (var writer = new StreamWriter("e:\\temp\\test.csv"))
    using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
    {
        var headings = new List<string>(records.First().Keys);
    
        foreach (var heading in headings)
        {
            csv.WriteField(heading);
        }
    
        csv.NextRecord();
    
        foreach (var item in records)
        {
            foreach (var heading in headings)
            {
                csv.WriteField(item[heading]);
            }
    
            csv.NextRecord();
        }
    }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-22
      • 2014-06-17
      • 1970-01-01
      • 1970-01-01
      • 2016-03-01
      相关资源
      最近更新 更多