gpt4 book ai didi

VB.NET:将 CSV 文件读入二维数组

转载 作者:行者123 更新时间:2023-12-04 06:28:07 24 4
gpt4 key购买 nike

我正在从事一个项目,该项目要求我从 CSV 文件中获取值。我必须对这些值进行进一步处理,如果我可以将这些值放在 2D 数组中,那就太好了。 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com