How to read a CSV file into a .NET Datatable

后端 未结 22 2420
野性不改
野性不改 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 05:49

    Here's a solution that uses ADO.Net's ODBC text driver:

    Dim csvFileFolder As String = "C:\YourFileFolder"
    Dim csvFileName As String = "YourFile.csv"
    
    'Note that the folder is specified in the connection string,
    'not the file. That's specified in the SELECT query, later.
    Dim connString As String = "Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=" _
        & csvFileFolder & ";Extended Properties=""Text;HDR=No;FMT=Delimited"""
    Dim conn As New Odbc.OdbcConnection(connString)
    
    'Open a data adapter, specifying the file name to load
    Dim da As New Odbc.OdbcDataAdapter("SELECT * FROM [" & csvFileName & "]", conn)
    'Then fill a data table, which can be bound to a grid
    Dim dt As New DataTableda.Fill(dt)
    
    grdCSVData.DataSource = dt
    

    Once filled, you can value properties of the datatable, like ColumnName, to make utilize all the powers of the ADO.Net data objects.

    In VS2008 you can use Linq to achieve the same effect.

    NOTE: This may be a duplicate of this SO question.

提交回复
热议问题