使用CsvHelper从CSV文件获取单元格值时出现问题

时间:2018-06-22 05:45:45

标签: c# csv csvhelper

        using (var sr = new StreamReader("myfile.csv))
        {
            var reader = new CsvReader(sr);
            List<dynamic> csvRecords = reader.GetRecords<dynamic>().ToList();

            //this works
            foreach (var row in csvRecords)
            {
                foreach (var item in row)
                {
                    var z = item.Value;
                }
            }

            //this should work, error message below
            foreach (var row in csvRecords)
            {
                var z = row[0].Value;
            }
        }

错误

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:无法将[]索引应用于类型'System.Dynamic.ExpandoObject

2 个答案:

答案 0 :(得分:1)

根据文档,您可以使用Read()

获取字段
using (var reader = new StreamReader("myfile.csv)) {
    var csv = new CsvReader( reader );
    while(csv.Read()) {//This will advance the reader to the next record.

        //You can use an indexer to get by position or name. 
        //This will return the field as a string

        // By position
        var field = csv[0];

        // By header name
        var field = csv["HeaderName"];
    }
}

引用https://joshclose.github.io/CsvHelper/reading#getting-fields

答案 1 :(得分:0)

您的row实现了IDictionary<String, object>接口explicitly,因此,要获取该值,您必须先强制​​转换行实例,然后再使用ElementAt(0).Value或寻址列名的值:

//this works fine
foreach (IDictionary<string, object> row in csvRecords)
{
     var z = row["column name"];
}

//and this works too 
foreach (IDictionary<string, object> row in csvRecords)
{
      var z = row.ElementAt(0).Value;
}