我正在尝试将 Excel 工作表导入 datagridview,但遇到错误:“数据库或对象是只读的。” 但是,我引用的工作簿没有应用只读属性。话虽如此,如果我的应用程序正在运行,我正在连接的工作簿已经打开,所以我怀疑这就是我遇到此错误的原因。工作簿已打开,因此在尝试填充数据集时对系统显示为只读。
我的这个假设是对的吗?如果我要连接的工作簿是打开的,他们是否可以使用 OleDB 连接将 Excel 工作表导入 datagridview?如果没有,是否有任何其他方法可以填充此 datagridview 而无需通过我的工作表进行大规模循环?我的代码如下:
Try
'connect to Excel data source and set gridview equal to dataset (entire sheet should be visible in gridview)
Dim MyConnection As System.Data.OleDb.OleDbConnection
Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
Dim connstring As String = "Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source=" & StatVar.workbookName & ";Extended Properties=""Excel 12.0;HDR=YES;Readonly=False"";" 'may need to use different MS provider and lower OLEDB for .xls files (Microsoft.Jet.OLEDB4.0...Excel 8.0) kind of sketchy though
MyConnection = New System.Data.OleDb.OleDbConnection(connstring) 'create a new data connection to Excel data source
MyCommand = New System.Data.OleDb.OleDbDataAdapter("select * from [Budget$]", MyConnection) 'query the sheet - select all data
MyCommand.TableMappings.Add("Table", "Table") 'map data selection as table
StatVar.DtSet1 = New System.Data.DataSet 'create new data set
MyCommand.Fill(StatVar.DtSet1) 'fill data set with table
Form14.DataGridView1.DataSource = StatVar.DtSet1.Tables(0) 'populate gridview with data set table
MyConnection.Close()
Form14.ShowDialog()
Catch exc As Exception
MessageBox.Show("There was a problem loading this database. Please contact an administrator if the problem continues." & vbNewLine & vbNewLine & "Error: " & exc.Message)
End Try
我在这里遇到错误:
MyCommand.Fill(StatVar.DtSet1)