使用 CsvHelper 从 CSV 文件获取单元格值的问题

Issue getting cell value from CSV file using 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

的表达式

您的 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;
}

根据文档,您可以使用 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