我正在尝试通过vb.net将Excel文件导入Access数据库 我们的想法是,客户可以将数据导出到Excel中,对其进行修改,添加,删除,然后将其导回。
导出的数据格式与要导入的表格完全相同。 我使用下面的代码:
Try
Dim strFileName As String = String.Empty
Dim XLda As New OleDbDataAdapter
Dim ExcelTables As New DataTable
Dim StrSelect = "SELECT * FROM [{0}]"
OpenFileDialog1.FileName = ""
OpenFileDialog1.InitialDirectory = mdlGlobalStuff.sMasterDataPath
OpenFileDialog1.Filter = "Excel|*.xls|All files (*.*)|*.*"
If OpenFileDialog1.ShowDialog() <> Windows.Forms.DialogResult.OK Then
Exit Sub
End If
strFileName = OpenFileDialog1.FileName
Dim MyXLConnection As New OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & strFileName & ";Extended Properties=Excel 8.0;")
Using MyXLConnection
Using cmd As New OleDbCommand
cmd.Connection = MyXLConnection
cmd.CommandText = "INSERT INTO [MS Access;Database=InvoicingToolDB.accdb].[tbl_Bases] SELECT * FROM [Sheet1$]"
If MyXLConnection.State = ConnectionState.Open Then
MyXLConnection.Close()
End If
MyXLConnection.Open()
cmd.ExecuteNonQuery()
End Using
End Using
Catch ex As Exception
MsgBox("ImportLinkLabel_LinkClicked: Importing Base data" & vbCrLf & ErrorToString())
End Try
我总是有一条错误消息说:
Unrecognized database format 'c:\--path to db--\InvoicingToolDB.accdb'
路径是正确的,我不明白为什么格式不会被识别。
答案 0 :(得分:0)
好的,我发现了这个问题。 OLEDB提供程序版本不正确(4.0不是读取.accdb格式,而只是旧的.mdb格式) 替换:
Dim MyXLConnection As New OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & strFileName & ";Extended Properties=Excel 8.0;")
使用:
Dim MyXLConnection As New leDbConnection("provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & strFileName & ";Extended Properties=Excel 8.0;")
完美无缺。