如何在vb未打开时从vb中读取excel文件

时间:2012-05-04 07:46:32

标签: vb.net excel-2007

我有一个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`

1 个答案:

答案 0 :(得分: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