我正在處理一個需要我從CSV文件中獲取值的項目。我必須用這些值做進一步的處理,如果我可以在2D數組中使用這些值,那將會很棒。 CSV文件的行數和列數會定期更改。VB.NET:將CSV文件讀取到2D數組中
我無法將這些值轉換爲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
相關:http://stackoverflow.com/questions/906841/csv-parser-閱讀器爲C, http://stackoverflow.com/questions/1103495/is-there-a-proper-way-to-read-csv-files, http://stackoverflow.com/questions/3509640/ reading-csv-file-c – 2011-04-25 09:40:13