读取CSV文件并将值存储到数组中

本文介绍了如何使用C#读取CSV文件,特别是如何将数据存储到数组中。讨论了多种方法,包括StreamReader、CsvHelper库、TextFieldParser以及处理头行和空行的技巧,为高效处理CSV数据提供了方案。
摘要由CSDN通过智能技术生成

本文翻译自: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: 这是我投票最多的答案的变体:

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

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

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

#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 从上面的文章中获取下面的代码示例

static void Main()
{
    string csv_file_path=@"C:\Users\Administrator\Desktop\test.csv";

    DataTable csvData = GetDataTabletFromCSVFile(csv_file_path);

    Console.WriteLine("Rows count:" + csvData.Rows.Count);

    Console.ReadLine();
}


private static DataTable GetDataTabletFromCSVFile(string csv_file_path)
{
    DataTable csvData = new DataTable();

    try
    {

    using(TextFieldParser csvReader = new TextFieldParser(csv_file_path))
        {
            csvReader.SetDelimiters(new string[] { "," });
            csvReader.HasFieldsEnclosedInQuotes = true;
            string[] colFields = csvReader.ReadFields();
            foreach (string column in colFields)
            {
                DataColumn datecolumn = new DataColumn(column);
                datecolumn.AllowDBNull = true;
                csvData.Columns.Add(datecolumn);
            }

            while (!csvReader.EndOfData)
            {
                string[] fieldData = csvReader.ReadFields();
                //Making empty value as null
                for (int i = 0; i < fieldData.Length; i++)
                {
                    if (fieldData[i] == "")
                    {
                        fieldData[i] = null;
                    }
                }
                csvData.Rows.Add(fieldData);
            }
        }
    }
    catch (Exception ex)
    {
    }
    return csvData;
}

#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. 您可以将定界符设置为任何您喜欢的。

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

#6楼

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

    var lines = File.ReadAllLines(path).Select(a => a.Split(';'));
    var csv = (from line in lines               
               select (from col in line
               select col).Skip(1).ToArray() // skip the first column
              ).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: 注意 :通过使用以下代码,您可以轻松获得标题和第一栏:

    var coltitle = (from line in lines 
                    select line.Skip(1).ToArray() // skip 1st column
                   ).Skip(1).Take(1).FirstOrDefault().ToArray(); // take the 2nd row
    var rowtitle = (from line in lines select line[0] // take 1st column
                   ).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语句之间。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值