我正在开发一个项目,需要我从 CSV 文件中获取值。我必须对这些值进行进一步处理,如果我可以将这些值放入二维数组中,那就太好了。 CSV 文件的行数和列数定期更改。
我无法将这些值放入 VB.NET/C# 中的二维数组中。我可以帮忙吗?
这是我使用的代码:
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
最佳答案
您使用 CsvReader from here轻松方便地将 csv(或其他类似数据)读取到 DataTable(或 IDataReader)中。对于这种情况,它始终是我的第一选择 - 快速且非常强大。
关于VB.NET:将 CSV 文件读入二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5777038/