当前位置:   article > 正文

读取CSV文件并将值存储到数组中_c++ 将csv转成数组

c++ 将csv转成数组

本文翻译自:Reading CSV file and storing values into an array

I am trying to read a *.csv -file. 我正在尝试读取*.csv文件。

The *.csv -file consist of two columns separated by semicolon (" ; "). *.csv文件由两列组成,两列之间用分号(“ ; ”)分隔。

I am able to read the *.csv -file using StreamReader and able to separate each line by using the Split() function. 我能够使用StreamReader读取*.csv文件,并能够通过使用Split()函数分隔每一行。 I want to store each column into a separate array and then display it. 我想将每一列存储到一个单独的数组中,然后显示它。

Is it possible to do that? 有可能这样做吗?


#1楼

参考:https://stackoom.com/question/MALf/读取CSV文件并将值存储到数组中


#2楼

Just came across this library: https://github.com/JoshClose/CsvHelper 刚遇到此库: https : //github.com/JoshClose/CsvHelper

Very intuitive and easy to use. 非常直观且易于使用。 Has a nuget package too which made is quick to implement: http://nuget.org/packages/CsvHelper/1.17.0 . 也有一个可以快速实现的nuget包: http ://nuget.org/packages/CsvHelper/1.17.0。 Also appears to be actively maintained which I like. 我也很喜欢积极维护。

Configuring it to use a semi-colon is easy: https://github.com/JoshClose/CsvHelper/wiki/Custom-Configurations 配置它以使用分号很容易: https : //github.com/JoshClose/CsvHelper/wiki/Custom-Configurations


#3楼

Here is my variation of the top voted answer: 这是我投票最多的答案的变体:

  1. var contents = File.ReadAllText(filename).Split('\n');
  2. var csv = from line in contents
  3. select line.Split(',').ToArray();

The csv variable can then be used as in the following example: 然后,可以在以下示例中使用csv变量:

  1. int headerRows = 5;
  2. foreach (var row in csv.Skip(headerRows)
  3. .TakeWhile(r => r.Length > 1 && r.Last().Trim().Length > 0))
  4. {
  5. String zerothColumnValue = row[0]; // leftmost column
  6. var firstColumnValue = row[1];
  7. }

#4楼

You can use Microsoft.VisualBasic.FileIO.TextFieldParser dll in C# for better performance 您可以在C#中使用Microsoft.VisualBasic.FileIO.TextFieldParser dll,以获得更好的性能

get below code example from above article 从上面的文章中获取下面的代码示例

  1. static void Main()
  2. {
  3. string csv_file_path=@"C:\Users\Administrator\Desktop\test.csv";
  4. DataTable csvData = GetDataTabletFromCSVFile(csv_file_path);
  5. Console.WriteLine("Rows count:" + csvData.Rows.Count);
  6. Console.ReadLine();
  7. }
  8. private static DataTable GetDataTabletFromCSVFile(string csv_file_path)
  9. {
  10. DataTable csvData = new DataTable();
  11. try
  12. {
  13. using(TextFieldParser csvReader = new TextFieldParser(csv_file_path))
  14. {
  15. csvReader.SetDelimiters(new string[] { "," });
  16. csvReader.HasFieldsEnclosedInQuotes = true;
  17. string[] colFields = csvReader.ReadFields();
  18. foreach (string column in colFields)
  19. {
  20. DataColumn datecolumn = new DataColumn(column);
  21. datecolumn.AllowDBNull = true;
  22. csvData.Columns.Add(datecolumn);
  23. }
  24. while (!csvReader.EndOfData)
  25. {
  26. string[] fieldData = csvReader.ReadFields();
  27. //Making empty value as null
  28. for (int i = 0; i < fieldData.Length; i++)
  29. {
  30. if (fieldData[i] == "")
  31. {
  32. fieldData[i] = null;
  33. }
  34. }
  35. csvData.Rows.Add(fieldData);
  36. }
  37. }
  38. }
  39. catch (Exception ex)
  40. {
  41. }
  42. return csvData;
  43. }

#5楼

I have been using csvreader.com(paid component) for years, and I have never had a problem. 我已经使用csvreader.com(付费组件)多年了,我从来没有遇到过问题。 It is solid, small and fast, but you do have to pay for it. 它坚固,小巧且快速,但您必须为此付出代价。 You can set the delimiter to whatever you like. 您可以将定界符设置为任何您喜欢的。

  1. using (CsvReader reader = new CsvReader(s) {
  2. reader.Settings.Delimiter = ';';
  3. reader.ReadHeaders(); // if headers on a line by themselves. Makes reader.Headers[] available
  4. while (reader.ReadRecord())
  5. ... use reader.Values[col_i] ...
  6. }

#6楼

If you need to skip (head-)lines and/or columns, you can use this to create a 2-dimensional array: 如果需要跳过(标题)行和/或列,则可以使用它来创建二维数组:

  1. var lines = File.ReadAllLines(path).Select(a => a.Split(';'));
  2. var csv = (from line in lines
  3. select (from col in line
  4. select col).Skip(1).ToArray() // skip the first column
  5. ).Skip(2).ToArray(); // skip 2 headlines

This is quite useful if you need to shape the data before you process it further (assuming the first 2 lines consist of the headline, and the first column is a row title - which you don't need to have in the array because you just want to regard the data). 如果您需要先对数据进行整形,然后再进行进一步处理(假设前两行由标题组成,并且第一列是行标题),则不需要在数组中使用,这非常有用。想要考虑数据)。

NB You can easily get the headlines and the 1st column by using the following code: 注意 :通过使用以下代码,您可以轻松获得标题和第一栏:

  1. var coltitle = (from line in lines
  2. select line.Skip(1).ToArray() // skip 1st column
  3. ).Skip(1).Take(1).FirstOrDefault().ToArray(); // take the 2nd row
  4. var rowtitle = (from line in lines select line[0] // take 1st column
  5. ).Skip(2).ToArray(); // skip 2 headlines

This code example assumes the following structure of your *.csv file: 此代码示例假定*.csv文件的以下结构:

CSV矩阵

Note: If you need to skip empty rows - which can by handy sometimes, you can do so by inserting 注意:如果您需要跳过空行-有时很方便,则可以通过插入

    where line.Any(a=>!string.IsNullOrWhiteSpace(a))

between the from and the select statement in the LINQ code examples above. 在上述LINQ代码示例中的fromselect语句之间。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/529199?site
推荐阅读
相关标签
  

闽ICP备14008679号