How to read a CSV file into a .NET Datatable

后端 未结 22 2453
野性不改
野性不改 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:03

    Can't resist adding my own spin to this. This is so much better and more compact than what I've used in the past.

    This solution:

    • Does not depend on a database driver or 3rd party library.
    • Will not fail on duplicate column names
    • Handles commas in the data
    • Handles any delimiter, not just commas (although that is the default)

    Here's what I came up with:

      Public Function ToDataTable(FileName As String, Optional Delimiter As String = ",") As DataTable
        ToDataTable = New DataTable
        Using TextFieldParser As New Microsoft.VisualBasic.FileIO.TextFieldParser(FileName) With
          {.HasFieldsEnclosedInQuotes = True, .TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited, .TrimWhiteSpace = True}
          With TextFieldParser
            .SetDelimiters({Delimiter})
            .ReadFields.ToList.Unique.ForEach(Sub(x) ToDataTable.Columns.Add(x))
            ToDataTable.Columns.Cast(Of DataColumn).ToList.ForEach(Sub(x) x.AllowDBNull = True)
            Do Until .EndOfData
              ToDataTable.Rows.Add(.ReadFields.Select(Function(x) Text.BlankToNothing(x)).ToArray)
            Loop
          End With
        End Using
      End Function
    

    It depends on an extension method (Unique) to handle duplicate column names to be found as my answer in How to append unique numbers to a list of strings

    And here's the BlankToNothing helper function:

      Public Function BlankToNothing(ByVal Value As String) As Object 
        If String.IsNullOrEmpty(Value) Then Return Nothing
        Return Value
      End Function
    

提交回复
热议问题