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


本文实例讲述了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即可


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3