Diagnosing an OLEDB exception when Quering Excel 2

2019-01-12 02:04发布

问题:

To query an excel sheet via SQL, I used to use either:

Dim excelConnectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strPath + ";Extended Properties=""Excel 8.0;IMEX=1;HDR=YES;"""

or

Dim excelConnectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= " + strPath + ";Extended Properties=""Excel 12.0;IMEX=1;HDR=YES;"""

Now this worked fine until I installed Office 2010.

Now I get a

Microsoft.Ace.OLEDB.12.0 provider is not registered on this machine exception.

How can I find out the correct connection string/provider?

回答1:

Perhaps you uninstalled the Access Database Engine (ACE) components? They are still available for download from MSDN as 2007 Office System Driver: Data Connectivity Components.



回答2:

I believe for Excel 2010 it is :

Dim excelConnectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Password="""";User ID=Admin;Data Source=D:\\MyDocs\\oledb.xlsx;Mode=Share Deny Write;Extended Properties=""HDR=YES;"";Jet OLEDB:Engine Type=37"

This appears to work in my visual studio, I got Excel to generate the query string and it had the extra entry in it.



回答3:

I downloaded and installed Office System Driver: Data Connectivity Components as advised above - and the below code worked:

    string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Password=\"\";User ID=Admin;Data Source=d:\\Sample.xlsx;Mode=Share Deny Write;Extended Properties=\"HDR=YES;\";Jet OLEDB:Engine Type=37";

    OleDbConnection connection = new OleDbConnection(connectionString);

    try
    {
        connection.Open();

        OleDbCommand command = new OleDbCommand("SELECT * FROM [Sheet1$]", connection);
        OleDbDataAdapter adapter = new OleDbDataAdapter();
        adapter.SelectCommand = command;

        DataSet ds = new DataSet();
        adapter.Fill(ds);

        GridView1.DataSource = ds;
        GridView1.DataBind();

    }
    catch (Exception)
    {            
        //throw;
    }
    finally
    {
        connection.Close();
    }