VB.NET:将 CSV 文件读入二维数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5777038/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VB.NET: Reading a CSV file into a 2D array
提问by Arjun Vasudevan
I'm working on a project that requires me to take values from a CSV file. I've to do further processing with these values and it'd be great if I can have these values in a 2D array. The number of rows and columns of the CSV files changes at regular intervals.
我正在从事一个项目,该项目要求我从 CSV 文件中获取值。我必须对这些值进行进一步处理,如果我可以将这些值放在 2D 数组中,那就太好了。CSV 文件的行数和列数会定期更改。
I'm unable to take these values into a 2D array in VB.NET/C#. Can I please have some help on that?
我无法将这些值放入 VB.NET/C# 中的二维数组中。我可以请一些帮助吗?
Here the code that I used:
这里是我使用的代码:
Imports System.IO
Public Class Form1
Private Sub ReadCSVFileToArray()
Dim strfilename As String
Dim num_rows As Long
Dim num_cols As Long
Dim x As Integer
Dim y As Integer
Dim strarray(1, 1) As String
' Load the file.
strfilename = "test.csv"
'Check if file exist
If File.Exists(strfilename) Then
Dim tmpstream As StreamReader = File.OpenText(strfilename)
Dim strlines() As String
Dim strline() As String
strlines = tmpstream.ReadToEnd().Split(Environment.NewLine)
' Redimension the array.
num_rows = UBound(strlines)
strline = strlines(0).Split(",")
num_cols = UBound(strline)
ReDim strarray(num_rows, num_cols)
' Copy the data into the array.
For x = 0 To num_rows
strline = strlines(x).Split(",")
For y = 0 To num_cols
strarray(x, y) = strline(y)
Next
Next
' Display the data in textbox
For x = 0 To num_rows
For y = 0 To num_cols
TextBox1.Text = TextBox1.Text & strarray(x, y) & ","
Next
TextBox1.Text = TextBox1.Text & Environment.NewLine
Next
End If
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
ReadCSVFileToArray()
End Sub
End Class
回答by Marc Gravell
You use the CsvReader from hereto easily and conveniently read a csv (or other similar data) into a DataTable (or an IDataReader). It is always my first choice for this scenario - fast and pretty robust.
您可以使用此处的CsvReader轻松方便地将 csv(或其他类似数据)读入 DataTable(或 IDataReader)。对于这种情况,它始终是我的首选 - 快速且非常强大。
回答by JohnB
I'm not disagreeing with Marc Gravell, because you shouldn't try to re-invent the wheel. His solution would perform the best, and there can be many CSV format nuances that can screw up a simple parser such as the one demonstrated below.
我并不反对 Marc Gravell,因为您不应该尝试重新发明轮子。他的解决方案会表现得最好,并且可能有许多 CSV 格式的细微差别,可能会搞砸一个简单的解析器,例如下面演示的那个。
With that said, you asked for a CSV parser that returns a 2D array. The code below does just that (jagged array), and should work for a very simple CSV file. This skips a header row in the file.
话虽如此,您要求返回一个二维数组的 CSV 解析器。下面的代码就是这样做的(锯齿状数组),并且应该适用于一个非常简单的 CSV 文件。这会跳过文件中的标题行。
(sorry it's not in VB, but you can put it in a helper class in your project)
(抱歉它不在VB中,但您可以将其放在项目中的帮助类中)
private string[][] GetData(string fileName)
{
List<string[]> data = new List<string[]>();
using (StreamReader sr = new StreamReader(fileName))
{
bool headerRow = true;
string line;
while ((line = sr.ReadLine()) != null)
{
if (headerRow)
{
headerRow = false;
}
else
{
string[] split = line.Split(new char[] { ',' });
data.Add(split);
}
}
}
return data.ToArray();
}
回答by Erno
Parsing a CSV file can be pretty hard due to all the possible variations of CSV. See: http://en.wikipedia.org/wiki/Comma-separated_values
由于 CSV 的所有可能变体,解析 CSV 文件可能非常困难。请参阅:http: //en.wikipedia.org/wiki/Comma-separated_values
E.g., think about embedded quotes, commas etc. So it will not be a simple matter of reading lines/strings and splitting them.
例如,考虑嵌入引号、逗号等。因此读取行/字符串和拆分它们不是一个简单的问题。
Perhaps you are better of by using a third party library
也许您最好使用第三方库
回答by Chris Taylor
Since the number of columns and rows change frequently, you could use dynamic lists rather than a fixed 2D array.
由于列数和行数经常变化,您可以使用动态列表而不是固定的二维数组。
List<List<string>> data = new List<List<string>>();
Then as you parse the CSV file you can build up the data dynamically in the above structure, adding a new List<string>
to data
for each new row in the CSV file.
然后,当您解析 CSV 文件时,您可以在上述结构中动态构建数据,为 CSV 文件中的每个新行添加一个新的List<string>
to data
。
Update:The VB.NET equivalent is something like
更新:VB.NET 等价物类似于
data As New List(Of List(Of String))
That being said, @Mark Gravell's suggestion is a far better solution than doing this yourself.
话虽如此,@Mark Gravell 的建议是比自己做这件事更好的解决方案。