天天看點

讀取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:

這是我投票最多的答案的變體:
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代碼示例中的

from

select

語句之間。

繼續閱讀