[英]Reading a specific value in a cell in a .csv file in VB.NET
我的目标是在 a.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 文件中的最后一行。
在给定行号和列号时,如何使其仅返回 a.csv 文件中一个单元格的特定值?
如果您的 CSV 文件不是很大,最简单的方法是加载 memory 列表中的所有内容,然后提取所需的信息
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
不过要注意两点。
这是将该文件加载到 memory 并将其存储以供重复访问的示例:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.