點擊事件代碼.cs
PRotected void Button1_Click(object sender, EventArgs e) { string strPath = "d:/test.xls"; string mystring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source = '" + strPath + "';Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'"; //"Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = '" + strPath + "';Extended Properties=Excel 8.0"; OleDbConnection cnnxls = new OleDbConnection(mystring); OleDbDataAdapter myDa = new OleDbDataAdapter("select * from [Sheet1$]", cnnxls); DataSet myDs = new DataSet(); myDa.Fill(myDs); DataGrid1.DataSource = myDs.Tables[0]; DataGrid1.DataBind(); }
如果使用經(jīng)典的"Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = '" + strPath + "';Extended Properties=Excel 8.0"會報錯:外部表不是預(yù)期的格式
這是因為:Microsoft.Jet.OLEDB.4.0是Microsoft Jet引擎,這適用于2003版本(2003之前的我沒裝,所以也不知道能向下適應(yīng)到哪個版本),而在2007中,微軟對其旗下 access 與 Excel 的主要文件格式進行修改,并且重命名為 .accdb(Access 2007 數(shù)據(jù)庫文件)與 .xlsx(Excel 2007 文件),因此未被 Microsoft Jet 引擎所支持,不過微軟也很快的提出了 Microsoft Office 2007 Desktop Drivers: Data Connectivity Components 來支持。
解決方法就是把連接字符串中的數(shù)據(jù)提供者改為 Microsoft.ACE.OLEDB.12.0
新聞熱點
疑難解答