使用CsvHelper将CSV中的所有值读取到列表中

2o7dmzc5  于 7个月前  发布在  其他
关注(0)|答案(7)|浏览(68)

所以我一直在阅读,我不应该写自己的CSV阅读器/编写器,所以我一直在尝试使用通过nuget安装的CsvHelper库。CSV文件是一个灰度图像,行数是图像的高度,列数是宽度。我想将值逐行读取到单个List<string>List<byte>中。
到目前为止,我的代码是:

using CsvHelper;

public static List<string> ReadInCSV(string absolutePath)
{
    IEnumerable<string> allValues;

    using (TextReader fileReader = File.OpenText(absolutePath))
    {
        var csv = new CsvReader(fileReader);
        csv.Configuration.HasHeaderRecord = false;
        allValues = csv.GetRecords<string>
    }

    return allValues.ToList<string>();
}

字符串
但是allValues.ToList<string>()抛出了一个:

  • 用户代码未处理CsvallationException *
  • 在CsvHelper.dll中发生类型为“CsvHelper.Configuration. CsvHelpationException”的异常,但未在用户代码中处理 *
  • 其他信息:继承IELTS的类型无法自动Map。您是否意外调用了作用于单个记录的GetRecord或WriteRecord,而不是调用作用于记录列表的GetRecords或WriteRecords?*

GetRecords可能需要我自己的自定义类,但我只是希望将值作为一些基本类型或字符串。此外,我怀疑整行都被转换为单个字符串,而不是每个值都是一个单独的字符串。

xcitsw88

xcitsw881#

根据@Marc L的帖子,你可以试试这个:

public static List<string> ReadInCSV(string absolutePath) {
    List<string> result = new List<string>();
    string value;
    using (TextReader fileReader = File.OpenText(absolutePath)) {
        var csv = new CsvReader(fileReader);
        csv.Configuration.HasHeaderRecord = false;
        while (csv.Read()) {
           for(int i=0; csv.TryGetField<string>(i, out value); i++) {
                result.Add(value);
            }
        }
    }
    return result;
}

字符串

h43kikqp

h43kikqp2#

如果您所需要的只是数组中每一行的字符串值,则可以直接使用解析器。

var parser = new CsvParser( textReader );
while( true )
{
    string[] row = parser.Read();
    if( row == null )
    {
        break;
    }
}

字符串
http://joshclose.github.io/CsvHelper/#reading-parsing

更新

版本3支持阅读和写入IEnumerable属性。

idv4meu8

idv4meu83#

这里的重点是读取CSV的所有行,并将其转换为对象集合。我不知道为什么要将其作为字符串集合读取。如前所述,泛型ReadAll()可能最适合您。当您将其用于此目的时,此库会非常出色:

using System.Linq;

...
using (var reader = new StreamReader(path))
using (var csv = new CsvReader(reader))
{
    var yourList = csv.GetRecords<YourClass>().ToList();
}

字符串
如果您不使用ToList()-它将一次返回一条记录(为了更好的性能),请阅读https://joshclose.github.io/CsvHelper/examples/reading/enumerate-class-records

cvxl0en2

cvxl0en24#

请试试这个,这个对我很有效。

TextReader reader = File.OpenText(filePath);
            CsvReader csvFile = new CsvReader(reader);
            csvFile.Configuration.HasHeaderRecord = true;
            csvFile.Read();
            var records = csvFile.GetRecords<Server>().ToList();

字符串
服务器是一个实体类。这是我如何创建的。

public class Server
    {
        private string details_Table0_ProductName;
        public string Details_Table0_ProductName
        {
            get
            {
                return details_Table0_ProductName;
            }
            set
            {
                this.details_Table0_ProductName = value;
            }
        }

        private string details_Table0_Version;
        public string Details_Table0_Version
        {
            get
            {
                return details_Table0_Version;
            }
            set
            {
                this.details_Table0_Version = value;
            }
        }       
    }

pn9klfpd

pn9klfpd5#

你很接近了。这并不是说它试图将 row 转换为字符串。CsvHelper试图将行中的每个字段Map到您给予它的类型上的属性,使用标题行中给出的名称。此外,它不知道如何对IEnumerable类型(string实现)进行此操作,所以它只是在测试类型时自动Map到该点时抛出。
如果你的文件格式足够简单,你的文件格式看起来是--众所周知的字段格式,既没有转义符也没有引号分隔符--我看不出为什么你需要承担导入库的开销。你应该能够根据需要用System.IO.File.ReadLines()String.Split()枚举值。

//pseudo-code...you don't need CsvHelper for this
IEnumerable<string> GetFields(string filepath)
{
  foreach(string row in File.ReadLines(filepath))
  {
    foreach(string field in row.Split(',')) yield return field;
  }
}

字符串

zvms9eto

zvms9eto6#

下面的.NET代码可以将CVS文件中的所有单元格值转换为List<string>对象。测试它读取11列X 31行的CSV文件,所有单元格数据都读取成功。

首先安装CsvHelper 30.0.1,然后在代码上使用库

using CsvHelper;
using CsvHelper.Configuration;

字符串

然后,使用这些代码将单元格值保存到.NET列表字符串对象中

// Replace with your CSV file path
    string filePath = @"C:\Temp\MyRawData.csv";

    // Configure CSV Reader
    CsvConfiguration config = new CsvConfiguration(CultureInfo.InvariantCulture)
    { HasHeaderRecord = false };
    StreamReader reader = new StreamReader(filePath);

    // Declare List<string> Object to hold data later
    List<string> cellDataList = new List<string>();

    // Fetch all cells value
    using (var csv = new CsvReader(reader, config))
    {

        while (csv.Read())
        {
            int MaxIndex = csv.Parser.Count;
            for (var i = 0; i < MaxIndex; i++)
            {
                // Then Save into List<string> Object
                cellDataList.Add(csv.GetField<string>(i));
            }
        }
    }

pqwbnv8z

pqwbnv8z7#

static void WriteCsvFile(string filename, IEnumerable<Person> people)
    {

        StreamWriter textWriter = File.CreateText(filename);

        var csvWriter = new CsvWriter(textWriter, System.Globalization.CultureInfo.CurrentCulture);

        csvWriter.WriteRecords(people);

        textWriter.Close();

    }

字符串

相关问题