使用Oledb Connection将数据从.csv文件导入DataGrid()

时间:2015-03-13 05:08:41

标签: vb.net connection-string oledbconnection oledbcommand oledbdataadapter

当我运行此代码时,它会抛出错误

  

“'D:\ Projects \ MyTestProject \ temp \ 2195-1480834730_Athletes.csv'不是有效路径。请确保路径名拼写正确并且您已连接到文件所在的服务器。”

我正在尝试将数据从.csv文件导入datagrid。 FileName是D:\Projects\MyTestProject\temp\2195-1480834730_Athletes.csv

由于

Sub ExcelImportToGrid(ByVal filename As String, ByVal fileext As String)
        Dim strconn As String
        Dim ds As DataSet = New DataSet()
        Try
            If fileext = ".xlsx" Then
                strconn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filename + "; Extended Properties=Excel 12.0"
            ElseIf fileext = ".csv" Then
                strconn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" & filename & ";" + "Extended Properties=Text;"
            Else
                strconn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" & filename & ";" + "Extended Properties=Excel 8.0;"
            End If
            Dim da As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter("SELECT * FROM [Sheet1$]", strconn)
            da.TableMappings.Add("Table", "Excel Data")
            da.Fill(ds)
            DataGrid1.DataSource = ds.Tables(0).DefaultView
            DataGrid1.DataBind()
        Catch ex As Exception
            JS_Alert(ex.Message)
        End Try
    End Sub

1 个答案:

答案 0 :(得分:0)

在处理.csv / .txt文件时,“连接”字符串应该具有文件夹路径,而不是确切的文件路径。

并且Select查询应该具有文件名而不是工作表名称

"Select * from [" + "Filename.csv" + "];"