您可以在www.example.com(winforms)中搜索csv吗vb.net

t9eec4r0  于 2023-03-03  发布在  .NET
关注(0)|答案(2)|浏览(111)

我试图在csv中搜索日期,每个条目有几个字段,我真的很难找到我如何能做到这一点。我看了谷歌和一些(甚至很老)论坛,我似乎找不到任何东西以外的信息,vb.net有一个内置的csv工具。请原谅我的无知,我非常新的vb和只是试图弄清楚:)有人能帮忙吗?非常感谢提前

cgfeq70w

cgfeq70w1#

@大卫发布了一个完整快速的csv搜索方法:无论如何,这是一个“手动”和缓慢的方法来理解基本的阅读和搜索csv文件:(注意,字段内容中的分隔符将导致随机行为)

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
qij5mzcb

qij5mzcb2#

第一步是将CSV文件加载到内存中。您可以使用OleDb提供程序将CSV文件加载到DataTable(documentation)中,如下所示:https://stackoverflow.com/a/11120351/1920035
下一步是查询数据。DataTable类提供了Select方法(documentation),该方法允许您传递筛选表达式。要按日期值筛选,请将日期文字用磅号括起来,例如#2023-02-27#
最后一步是显示数据,但由于您在最初的帖子中没有提供足够的信息,我无法帮助您完成这一步。
以下是所有这些信息的汇总:

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

相关问题