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

标签 vb.net arrays csv

我正在开发一个项目,需要我从 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/

相关文章:

java - 如何使 Spring Controller 从 POJO 返回 CSV?

c# - C Sharp 中的 SqlDataAdapter 错误

arrays - PostgreSQL 数组数据类型到 JSON 对象

php - 在 php 中比较 2 个 csv 文件和 1 列

javascript - 拦截 JavaScript 数组访问器

javascript - 数组的 Angular 过滤器数组

python re.search 匹配 csv.reader 中的所有内容?

mysql - 检查是否存在。如果存在则不插入数据,如果不存在则插入数据

vb.net - 等待进程完成

ASP.NET Webmethod 总是返回 401