import data from excel 2003 to dataTable

怎甘沉沦 提交于 2020-01-04 13:45:55

问题


I am importing excel worksheets to a datagridview using the following code:

Private Sub Browsimportbtn_Click(sender As Object, e As EventArgs) Handles Browsimportbtn.Click
    Dim textpath As String
    Dim textpath1 As String

    Dim opf As New OpenFileDialog
    If opf.ShowDialog = 1 Then
        textpath = opf.FileName
        textpath1 = opf.SafeFileName
        textpath1 = textpath1.Remove(textpath1.Length -4,4)

        Dim cnexcell As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & textpath & "; Extended Properties = ""Excel 12.0 Xml;HDR=YES"";")
        Dim cmdE As New OleDbCommand("SELECT * FROM Feuil1", cnexcell)

        Try

            Dim daoledb As New OleDbDataAdapter
            Dim dset As New DataSet


            daoledb.SelectCommand = cmdE
            daoledb.Fill(dset, "Feuil1")
            DGVmodele.DataSource = dset.Tables("Feuil1")

        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

    End If

End Sub

The code above is working well with .XLSX files (office 2007,2010...) but do not with .XLS and i don't know where is the issue.

Any suggestions?


回答1:


The issue is in the connectionstring.

You are specifying the Excel 12 as a version in the connection string which is related to 2007 or higher. Try using this function to build the connectionstring

Public Function BuildConnectionString(Byval m_strExcelPath as String) As String
    If m_strExcelPath.Substring(m_strExcelPath.LastIndexOf(".")).ToLower = ".xlsx" Then
        Return "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & m_strExcelPath & ";Excel 12.0;HDR=YES;IMEX=1"
    Else
        Return "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & m_strExcelPath & ";Excel 8.0;HDR=YES;IMEX=1"
    End If
End Function



回答2:


Try using this instead.

"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & m_strExcelPath &  ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'"

It is unadvisable to use the JET OLEDB because it is outdated. If you really want to use it, you might need to reinstall Access Database Engine 2003.

Also, I heard there's also a bug regarding this.



来源:https://stackoverflow.com/questions/48102655/import-data-from-excel-2003-to-datatable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!