Visual Basic How do I read a CSV file and display the values in a datagrid?

后端 未结 4 1495
[愿得一人]
[愿得一人] 2021-01-06 07:49

I\'m using VB 2005, how do I open a CSV file and read the columns/rows and display the values in a datagrid?

CSV file example: jsmith,jsmith@hotmail.com

I th

4条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-06 08:19

    Here's a simple 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 DataTable
    da.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.

提交回复
热议问题