在VB.NET中读取.csv文件中单元格中的特定值

时间:2020-06-25 21:18:06

标签: .net vb.net csv

我的目标是在.csv文件中查找单元格的特定值。 (最好不要使用任何额外的参考包) 例如,如果我有一个.csv文件,如下所示:

A, B, C, D
E, F, G, H
I, J, K, L
M, N, O, P

然后我想返回第2行和第3列上特定单元格的值,即G

我尝试了以下代码:

 Dim sData() As String
   
        csvPath = appPath & "/sample.csv" 
        Using sr As New StreamReader(csvPath)
            Dim counter As Integer = 0
            While Not sr.EndOfStream
                sData = sr.ReadLine().Split(","c)
                If counter > 2 Then
                    Dim Cell1 As String = sData(0).Trim()
                 
                    MessageBox.Show(Cell1)
                    TextBox1.Text = Curdate
                    TextBox2.Text = OrderId
                End If
                counter += 1


            End While
        End Using

发生的事情是,当运行此代码时,将弹出一个消息框,并列出.csv文件的每一行。文本框的作用是在csv文件中显示了最后一行。

当给出行号和列号时,如何使它仅返回.csv文件中一个单元格的特定值?

2 个答案:

答案 0 :(得分:2)

如果您的CSV文件不是很大,最简单的方法是将所有内容加载到内存列表中,然后提取所需的信息

Function GetValue(row As Integer, col As Integer) As String
    
    Dim csvPath = "/sample.csv"
    Dim result As String = String.Empty
    Dim lines = File.ReadAllLines(csvPath)
    If row < lines.Length Then
        Dim cols = lines(row).Split(","c)
        If col < cols.Length Then
            result = cols(col)
        End If
    End If
    Return result        
End Function

但是要注意两件事。

  1. 文件不应太大,因为此代码会将其完全加载到内存中。
  2. 请确保不要在循环中调用此方法,因为每次调用该方法都会从磁盘重新加载所有数据。在那种情况下,考虑创建一个类,在初始化时仅加载一次文件,然后调用与加载的数据一起使用的GetValue方法。

答案 1 :(得分:0)

下面是将文件加载到内存中并进行重复访问的示例:

Private data As New List(Of String())

Private Sub LoadData() ' call it ONCE (maybe from the Load() event?)
    data.Clear()
    csvPath = appPath & "/sample.csv"
    Using sr As New StreamReader(csvPath)
        While Not sr.EndOfStream
            data.Add(sr.ReadLine().Split(","c))
        End While
    End Using
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    ' these are one based values
    Dim row As Integer = 2
    Dim col As Integer = 3
    Dim value As String = GetCellValue(row, col)
    If Not IsNothing(value) Then
        MessageBox.Show(row & ", " & col & " = " & value)
    Else
        MessageBox.Show("Invalid Row/Col!")
    End If
End Sub

Private Function GetCellValue(ByVal row As Integer, ByVal col As Integer) As String
    If row >= 1 AndAlso row <= data.Count Then
        Dim arr As String() = data(row - 1)
        If col >= 1 AndAlso col <= arr.Length Then
            Return arr(col - 1)
        End If
    End If
    Return Nothing
End Function
相关问题