Imports System.IO
Public Class CSV
Private Sub scanCSV()
Dim sr As New StreamReader("d:\files\file.csv") 'useful method to read any strings file
Dim lineNum As Integer
sr.ReadLine() 'rem this line if your file has no header
While Not sr.EndOfStream ' stop loop when file eof
Dim line As String = sr.ReadLine() 'read entire line
For Each str As String In line.Split(",") 'split cut line into separated parts - separator =","
If IsDate(str) Then 'vb function to test if string is a valid date
'date found
MsgBox("date found in line N°" & lineNum & " date = " & str)
End If
Next
lineNum += 1 'increment line number
End While
end sub
end class
Private Function LoadCsv(path As String) As DataTable
Dim folder = IO.Path.GetDirectoryName(path)
Dim filename = IO.Path.GetFileName(path)
Dim connection = $"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={folder};Extended Properties=""text;HDR=No;FMT=Delimited"";"
Dim csv = New DataTable
Using adapter = New OleDbDataAdapter($"select * from [{filename}]", connection)
adapter.Fill(csv)
End Using
Return csv
End Function
Private Function FilterOnOrBeforeDate(csv As DataTable, column As String, value As DateTime) As DataRow()
Return csv.Select($"{column} <= #{value}#")
End Function
2条答案
按热度按时间cgfeq70w1#
@大卫发布了一个完整快速的csv搜索方法:无论如何,这是一个“手动”和缓慢的方法来理解基本的阅读和搜索csv文件:(注意,字段内容中的分隔符将导致随机行为)
qij5mzcb2#
第一步是将CSV文件加载到内存中。您可以使用OleDb提供程序将CSV文件加载到DataTable(documentation)中,如下所示:https://stackoverflow.com/a/11120351/1920035
下一步是查询数据。DataTable类提供了Select方法(documentation),该方法允许您传递筛选表达式。要按日期值筛选,请将日期文字用磅号括起来,例如
#2023-02-27#
。最后一步是显示数据,但由于您在最初的帖子中没有提供足够的信息,我无法帮助您完成这一步。
以下是所有这些信息的汇总: