欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

asp.net页面中如何获取Excel表的内容

程序员文章站 2023-11-30 10:33:28
asp.net页面中如何获取excel表的内容,具体内容介绍如下所示: 首先引用组件和命名空间 using microsoft.office.interop.e...

asp.net页面中如何获取excel表的内容,具体内容介绍如下所示:

首先引用组件和命名空间

using microsoft.office.interop.excel;
 using system.data.oledb;

然后把excel上传到指定路径

上传文件方法省略

最后把上传的excel变成dataset  (复制下面的方法就可以用了)

public dataset seachexcel(string str) //参数为excel的路径
  {
    oledbdataadapter da = new oledbdataadapter();
    dataset ds = new dataset();
    datatable dt = new datatable();
    string nametable = "";
    string context = "";
    try
    {
      //获取excel路径
      fileinfo info = new fileinfo(str);
      //获取文件的扩展名
      string fileext = info.extension;
      //判断用哪种连接方式
      if (fileext .tolower() ==".xls")
      {
        context = "provider=microsoft.jet.oledb.4.0;data source=" + str + ";extended properties='excel 8.0;hdr=no;imex=1';persist security info=false";
      }
      else if (fileext.tolower() == ".xlsx")
      {
        context = "provider=microsoft.ace.oledb.12.0; data source=" + str + ";extended properties='excel 12.0 xml;hdr=no;imex=1';persist security info=false";
      }
      //连接excel
      oledbconnection conn = new oledbconnection(context);
     //打开excel
      conn.open();
      dt=conn.getoledbschematable(oledbschemaguid.tables,null );
        if(dt!=null && dt.rows .count >0)
        {
          //获取sheet1表单的表名
          nametable = dt.rows[0]["table_name"].tostring();
          //获取sheet2表单的表名
          //nametable = dt.rows[1]["table_name"].tostring();
        }
        string sql = "select * from [" + nametable + "]";
        da = new oledbdataadapter(sql, conn);
        try
        {
          da.fill(ds,nametable); //把数据填充到dataset
        }  
        catch
        { }
        conn.close();
    }
    catch
    {
    }
    return ds; //反回dataset
}

asp.net读取excel表格数据的方法

其实读取excel表格中的数据和读取数据库中的数据是非常类似的,因为在某种程度上excel表格可以看成是一张一张的数据表。其二者的主要区别在于所使用的数据引擎不一样。

在本文的程序中,通过下列代码实现读取excel表格数据,具体如下:

string strdatapathphy = "c://1.xls";
string strcon = " provider = microsoft.jet.oledb.4.0 ; data source = " + strdatapathphy + ";extended properties=excel 8.0";
oledbconnection myconn = new oledbconnection(strcon);
string strcom = " select * from [sheet1$]";
myconn.open();
oledbdataadapter mycommand = new oledbdataadapter(strcom, myconn);
datatable dtdata = new datatable();
mycommand.fill(dtdata);
myconn.close();

由于可以把excel看左一个数据库,里面的工作表就可以看左每张数据库表,所以也可以对搜索结果进行筛选,例如:

复制代码 代码如下:

strcom = " select * from [sheet1$] where column1 <> '' ";

这样dtdata里面的数据就是[sheet1$]表中column1不为空的全部数据了

以上就是本文介绍asp.net页面中如何获取excel表的内容,希望对大家有所帮助