ASP.NET實現讀取Excel內容並在Web上顯示_實用技巧

來源:互聯網
上載者:User

本文執行個體講述了ASP.NET實現讀取Excel內容並在Web上顯示的方法,是非常實用的一個功能,分享給大家供大家參考。具體實現方法如下:

點擊事件代碼.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(); }

注意:

如果使用經典的"Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = '" + strPath + "';Extended Properties=Excel 8.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即可。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.