本文實例講述了ASP.NET實現(xiàn)讀取Excel內(nèi)容并在Web上顯示的方法,是非常實用的一個功能,。具體實現(xiàn)方法如下:
點擊事件代碼.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 的主要文件格式進(jìn)行修改,并且重命名為 .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即可。
新聞熱點
疑難解答
圖片精選