我有一个 vb 程序,它从 excel 表中读取数据并将其显示在 datagridview 中。这个程序的问题是它只能在打开 excel 文件时读取数据并显示它,但是当没有打开 excel 文件时,它会给出一个错误报告,即
System.Data.OleDb.OleDbException: External table is not in the expected format.
at System.Data.OleDb.OleDbConnectionInternal..ctor(OleDbConnectionString constr, OleDbConnection connection)
at System.Data.OleDb.OleDbConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup)
at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)
at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
at System.Data.OleDb.OleDbConnection.Open()
at System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)
at System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)
at System.Data.Common.DbDataAdapter.Fill(DataSet dataSet)
at mForm.Form1.Button1_Click(Object sender, EventArgs e) in D:\myWorld\projects\coffee\mForm\mForm\Form1.vb:line 16
有没有办法即使在未打开的情况下也能从该文件中读取?这是我用来获取数据并放入 datagridview 的代码:
`Try
Dim MyConnection As System.Data.OleDb.OleDbConnection
Dim DtSet As System.Data.DataSet
Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
MyConnection = New System.Data.OleDb.OleDbConnection _
("Provider=Microsoft.Jet.Oledb.4.0; Data Source=" & Application.StartupPath & "\Staff Contracts.xlsx; Extended Properties=Excel 8.0")
MyCommand = New System.Data.OleDb.OleDbDataAdapter _
("select * from [Staff Contracts$A3:K14]", MyConnection)
MyCommand.TableMappings.Add("Table", "TestTable")
DtSet = New System.Data.DataSet
MyCommand.Fill(DtSet)
DataGridView1.DataSource = DtSet.Tables(0)
MyConnection.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try`