How to read a CSV file into a .NET Datatable

后端 未结 22 2113
野性不改
野性不改 2020-11-22 05:12

How can I load a CSV file into a System.Data.DataTable, creating the datatable based on the CSV file?

Does the regular ADO.net functionality allow this?

22条回答
  •  孤街浪徒
    2020-11-22 06:00

     Public Function ReadCsvFileToDataTable(strFilePath As String) As DataTable
        Dim dtCsv As DataTable = New DataTable()
        Dim Fulltext As String
        Using sr As StreamReader = New StreamReader(strFilePath)
            While Not sr.EndOfStream
                Fulltext = sr.ReadToEnd().ToString()
                Dim rows As String() = Fulltext.Split(vbLf)
                For i As Integer = 0 To rows.Count() - 1 - 1
                    Dim rowValues As String() = rows(i).Split(","c)
                    If True Then
                        If i = 0 Then
                            For j As Integer = 0 To rowValues.Count() - 1
                                dtCsv.Columns.Add(rowValues(j))
                            Next
                        Else
                            Dim dr As DataRow = dtCsv.NewRow()
                            For k As Integer = 0 To rowValues.Count() - 1
                                dr(k) = rowValues(k).ToString()
                            Next
                            dtCsv.Rows.Add(dr)
                        End If
                    End If
                Next
            End While
        End Using
        Return dtCsv
    End Function
    

提交回复
热议问题