使用csvhelper进行映射/写入辅助

时间:2014-03-29 22:54:00

标签: c# csv map mapping csvhelper

请在csvhelper上快速帮助...

CSV: 名,姓氏

PersonMap:

    public override void CreateMap()
    {
        Map(x => x.Name).Name("Name");
        Map(x => x.LasName).Name("LastName");
    } 

人类:

  public string Name { get; set; }
  public string LastName { get; set; }

主:

 public void writePerson()
 {
        IEnumerable<Person> records;
        using (var r = new CsvReader(new StreamReader("person.csv")))
        {
            r.Configuration.RegisterClassMap<PersonMap>();
            records = r.GetRecords<Person>().ToList();     
        } 

        using (var w = new CsvWriter(new StreamWriter("person.csv")))
        {
            w.Configuration.RegisterClassMap<PersonMap>();
            w.WriteRecord(records); //rewrite csv list
            w.WriteField("John")); 
            w.WriteField("Doe");
            w.NextRecord();             
        }
    }

ERROR LINE:records = reader.GetRecords()。ToList();

错误: 没有找到标题记录。

3 个答案:

答案 0 :(得分:3)

好,所以我用以下内容修复了它:

写:

string persondata = "John, Doe";
using (FileStream fs = new FileStream("person.csv", FileMode.Append, FileAccess.Write))
        using (StreamWriter sw = new StreamWriter(fs))
        { sw.WriteLine(persondata); sw.Dispose(); }

读:

IEnumerable<Person> records;
using (var reader = new CsvReader(new StreamReader(@"person.csv")))
{
        reader.Configuration.RegisterClassMap<PersonMap>();
        records = reader.GetRecords<Person>();
}

答案 1 :(得分:1)

看起来你的person.csv没有第一行作为标题行,如下所示:

Name,LastName

请检查CSV文件。

答案 2 :(得分:0)

添加以下配置行

w.configuration.HasHeaderRecord = false;