External table is not in the expected format.

喜你入骨 提交于 2019-12-23 20:25:13

问题


I am creating a small application to import excel data into my database, when i click the button it crashes with the error

External table is not in the expected format.

I tried googling and changing the codes here and there but the problem still occurs. I tried saving the file as a .xls and when i run the code the page went offline with google chrome's This webpage is not available (Cannot even enter debugging)

Here is my code:

    string strConnection = ConfigurationManager.ConnectionStrings["---"].ConnectionString;

    String excelConnString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0\"", filePath);
    //Create Connection to Excel work book 
    using (OleDbConnection excelConnection = new OleDbConnection(excelConnString))
    {
        //Create OleDbCommand to fetch data from Excel 
        using (OleDbCommand cmd = new OleDbCommand("Select * from [Sheet1$]", excelConnection))
        {
            excelConnection.Open();
            using (OleDbDataReader dReader = cmd.ExecuteReader())
            {
                using (SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection))
                {
                    //Give your Destination table name 
                    sqlBulk.DestinationTableName = "TableName";
                    sqlBulk.WriteToServer(dReader);
                }
            }
        }
    }

回答1:


Assuming you have done all the preparations including installing Microsoft Access 2010 Runtime to acquire the relevant drivers try the following as I had success with it in the past.

If your input file is of a type *.xlsx trying replacing

Extended Properties="Excel 12.0"

in your connection string with

Extended Properties="Excel 12.0 Xml"

This issue normally happens with the problematic or mismatching format of Excel file so as a rule of thumb the first thing you would want to try is to open Excel and create a new .xlsx file with couple of sample data in it which you typed yourself (rather than copy/paste). You don't need much typing to test your code snippet. Couple of cells with the right info you're expecting will do. This approach eliminates having any problems with the actual Excel file rather than your C# code.

Let us know how you went.



来源:https://stackoverflow.com/questions/28923158/external-table-is-not-in-the-expected-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!