2012-05-04 122 views
0

我有一個從Excel表讀取數據並將其顯示在datagridview中的vb程序。這個程序的問題在於,它能夠讀取數據並顯示它的Excel文件被打開,但在未打開Excel文件,它提供了一個錯誤報告,只有當如何從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` 

回答

1

看起來您對Excel 2007文件使用Excel 2003連接字符串。嘗試使用一個連接字符串是這樣的:

var connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=""Excel 12.0;HDR=YES""" 

我使用此代碼讀取Excel文件服務器端(無需爲Microsoft Office安裝):

Public Function getData(selectCmd As String, filePath as string) As System.Data.DataTable 
    Dim dataTable As New DataTable() 
    Using conn As New OleDbConnection(connString) 
     Dim adapter As New OleDbDataAdapter(selectCmd, conn) 
     adapter.Fill(dataTable) 
    End Using 
    Return dataTable 
End Function 
+0

太謝謝你了。只是改變連接字符串已經完成了。我會嘗試其他代碼,不需要進行Microsoft安裝,但現在一切正常 – ken