1. 程式人生 > >c#讀取Execl表格資料

c#讀取Execl表格資料

Excel “External table is not in the expected format.” .

Question:

I'm trying to read an Excel (xlsx) file using the code shown below. I get an "External table is not in the expected format." error unless I have the file already open in Excel. In other words, I have to open the file in Excel first before I can read if from my C# program. The xlsx file is on a share on our network. How can I read the file without having to open it first? Thanks

string sql = "SELECT * FROM [Sheet1$]";  string excelConnection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathname + ";Extended Properties=/"Excel 8.0;HDR=YES;IMEX=1;/"";    using (OleDbDataAdapter adaptor = new OleDbDataAdapter(sql, excelConnection)) {  DataSet ds = new DataSet();  adaptor.Fill(ds);  }  

Answers:

"External table is not in the expected format." typically occurs when trying to use an Excel 2007 file with a connection string that uses: Microsoft.Jet.OLEDB.4.0 and Extended Properties=Excel 8.0

Using the following connection string seems to fix most problems.


public static string path = @"C:/src/RedirectApplication/RedirectApplication/301s.xlsx";  public static string connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;";
以上出處:

http://blog.csdn.net/ldl22847/article/details/6322339

解決方案1:

很多人換了2010後,問的最多的問題之一是2003裡最經典的ADO中的“provider=Microsoft.Jet.OLEDB.4.0”這句怎麼不能用了。

百度一下可以瞭解到,Microsoft.Jet.OLEDB.4.0是Microsoft Jet引擎,這適用於2003版本(2003之前的我沒裝,所以也不知道能向下適應到哪個版本),而在2007中,微軟對其旗下 Access 與 Excel 的主要檔案格式進行修改,並且重新命名為 .accdb(Access 2007 資料庫檔案)與 .xlsx(Excel 2007 檔案),因此未被 Microsoft Jet 引擎所支援,不過微軟也很快的提出了Microsoft Office 2007 Desktop Drivers: Data Connectivity Components 來支援,目前的解決方法就是把連線字串中的資料提供者改為Microsoft.ACE.OLEDB.12.0

總上所述:

//2003(Microsoft.Jet.Oledb.4.0)
string strConn = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'", excelFilePath);

//2010(Microsoft.ACE.OLEDB.12.0)
string strConn = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'", excelFilePath);

解決方案2: 用記事本開啟你的excel檔案,看看顯示是否為亂碼。
若是亂碼,我這邊測試是不會提示這個錯誤的,可以成功匯入。 若是html程式碼,則表示你的excel檔案格式不是標準的excel格式,才會提示“外部表不是預期的格式”的錯誤; 總結:如果格式不正確,則通過excel軟體另存為標準的2003版本的格式 此部分來源於:http://blog.csdn.net/jiajiayouba/article/details/7531707