How do you read a CSV file and display the results in a grid in Visual Basic 2010?

前端 未结 7 1453
死守一世寂寞
死守一世寂寞 2020-12-29 07:56

How do you read a CSV file and display the results in a grid in Visual Basic 2010? This sounds so simple but I still can\'t find the answer to it after googling for a while.

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-29 08:39

    Consider this snippet of code. Modify as you see fit, or to fit your requirements. You'll need to have Imports statements for System.IO and System.Data.OleDb.

    Dim fi As New FileInfo("c:\foo.csv")
    Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Text;Data Source=" & fi.DirectoryName
    
    Dim conn As New OleDbConnection(connectionString)
    conn.Open()
    
    'the SELECT statement is important here, 
    'and requires some formatting to pull dates and deal with headers with spaces.
    Dim cmdSelect As New OleDbCommand("SELECT Foo, Bar, FORMAT(""SomeDate"",'YYYY/MM/DD') AS SomeDate, ""SOME MULTI WORD COL"", FROM " & fi.Name, conn)
    
    Dim adapter1 As New OleDbDataAdapter
    adapter1.SelectCommand = cmdSelect
    
    Dim ds As New DataSet
    adapter1.Fill(ds, "DATA")
    
    myDataGridView.DataSource = ds.Tables(0).DefaultView 
    myDataGridView.DataBind
    conn.Close()
    

提交回复
热议问题