服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|

服务器之家 - 编程语言 - ASP.NET教程 - ASP.NET实现读取Excel内容并在Web上显示

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

2019-12-07 14:29shichen2014 ASP.NET教程

这篇文章主要介绍了ASP.NET实现读取Excel内容并在Web上显示,很实用的一个技巧,需要的朋友可以参考下

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

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

?
1
2
3
4
5
6
7
8
9
10
11
12
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即可

延伸 · 阅读

精彩推荐