使用Kent Boogaart CSV写入CSV文件的指定列

时间:2011-12-28 06:33:00

标签: c# csv

我有以下场景:我的数据库中有五个字段(名称,电子邮件,地址等),然后是另外n个用户定义的字段,例如我可以添加自定义字段,如ID号,血型或任何内容对于那件事,以及我喜欢的那些。我现在需要把它放到一个CSV文件中。但问题是现在所有字段都是必需的,因此我不能只将标题添加到CSV文件中,然后按顺序添加数据,因为数据可能不在正确的列中。我需要做的是这样的事情:

  1. 添加预定义标题

  2. 添加其余自定义标题

  3. 添加预定义数据

  4. 添加自定义数据

  5. 我的问题是第4步。我需要的是能够将数据添加到指定的列,我似乎无法在KBCSV中找到如何执行此操作。

    我目前正在做的是:

    List<string> data = new List<string>();
    //Add all predefined data to the data object
    foreach (CustomDataItem cdi in CustomData)
    {
        data.Add(cdi.Value);
    }
    writer.WriteDataRecord(data);
    //writer is a Kent.Boogaart.KBCsv.CsvWriter
    

    这种方法的问题是CustomData长度和csv头长度无法匹配,这意味着我将在错误的列中包含值。有没有办法将数据值添加到指定的列?

2 个答案:

答案 0 :(得分:0)

为什么不在这里使用字典,然后在csv文件中写入时检查字典中的coreect序列列是否存在键

  Dictionary<string, string> data = new Dictionary<string, string>();
        //Add all predefined data to the data object 
        foreach (CustomDataItem cdi in CustomData)
        {
            data.Add(cdi.ColumnName, cdi.Value);
        } 

答案 1 :(得分:0)

你可以尝试这个

      IDictionary<string, List<string>> dictionary = new Dictionary<string, List<string>>();
      if (!dictionary.ContainsKey(key))
      {
          dictionary.Add(key, new List<string>());
      }
      dictionary[key].Add(value);
相关问题