当前位置:Gxlcms > asp.net > ASP.NET实现读取Excel内容并在Web上显示

ASP.NET实现读取Excel内容并在Web上显示

时间:2021-07-01 10:21:17 帮助过:14人阅读

本文实例讲述了ASP.NET实现读取Excel内容并在Web上显示的方法,是非常实用的一个功能,分享给大家供大家参考。具体实现方法如下:

点击事件代码.cs代码如下:

  1. protected void Button1_Click(object sender, EventArgs e)
  2. {
  3. string strPath = "d:/test.xls";
  4. string mystring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source = '" + strPath + "';Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
  5. //"Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = '" + strPath + "';Extended Properties=Excel 8.0";
  6. OleDbConnection cnnxls = new OleDbConnection(mystring);
  7. OleDbDataAdapter myDa = new OleDbDataAdapter("select * from [Sheet1$]", cnnxls);
  8. DataSet myDs = new DataSet();
  9. myDa.Fill(myDs);
  10. DataGrid1.DataSource = myDs.Tables[0];
  11. DataGrid1.DataBind();
  12. }

注意:

如果使用经典的"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即可

人气教程排行