ASP.NET导出数据到Excel的实现方法

 更新时间:2013年07月23日 11:02:29   作者:  
在做asp.net程序时涉及到数据显示的时候多数会要求打印,而网页上的打印格式往往又不能满足需求,经常用的方法就是导入到Excel以后再进行打印。(仿佛这已经是老生常谈)今天在网上搜了一段打印的代码,觉得不错,需要打印的朋友可以看看。
网上好些代码的原理大致与此类似,同样都存在一个问题,就是:
  类型“GridView”的控件“ctl00_center_GridView1”必须放在具有 runat=server 的窗体标记内。 说明: 执行当前 Web 请求期间,出现未处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。 异常详细信息:System.Web.HttpException: 类型“GridView”的控件“ctl00_center_GridView1”必须放在具有 runat=server 的窗体标记内。
  这段错误描述是我在注释了这段程序是报的错,
复制代码 代码如下:

//publicoverridevoidVerifyRenderingInServerForm(Controlcontrol)
//{
//  //base.VerifyRenderingInServerForm(control);
//}

  虽然这个方法里的内容也被注释了,也就是说这是个空方法,但是如果没有个方法,程序就会报上面那个错误。最初见到这段错误说明是想到了以前做ajax程序时报的一个错误很是类似。同样是因为没有重写VerifyRenderingInServerForm方法所致。在此提醒使用的朋友注意,下面贴出导出到Excel的代码
复制代码 代码如下:

usingSystem;
usingSystem.Data;
usingSystem.Configuration;
usingSystem.Collections;
usingSystem.Web;
usingSystem.Web.Security;
usingSystem.Web.UI;
usingSystem.Web.UI.WebControls;
usingSystem.Web.UI.WebControls.WebParts;
usingSystem.Web.UI.HtmlControls;
usingSystem.IO;
///<summary>
///ToExcleHelper的摘要说明
///</summary>
  publicclassExportHelper
  {
    publicstaticvoidExportToExcel(IListdataList,string[]fields,string[]headTexts,stringtitle)
    {
      GridViewgvw=newGridView();
      intColCount,i;
      //如果筛选的字段和对应的列头名称个数相对的情况下只导出指定的字段
      if(fields.Length!=0&&fields.Length==headTexts.Length)
      {
        ColCount=fields.Length;
        gvw.AutoGenerateColumns=false;
        for(i=0;i<ColCount;i++)
        {
          BoundFieldbf=newBoundField();
          bf.DataField=fields[i];
          bf.HeaderText=headTexts[i];
          gvw.Columns.Add(bf);
        }
      }
      else
      {
        gvw.AutoGenerateColumns=true;
      }
      SetStype(gvw);
      gvw.DataSource=dataList;
      gvw.DataBind();
      ExportToExcel(gvw,title);
    }
    ///<summary>
    ///导出数据到Excel
    ///</summary>
    ///<paramname="DataList">IListData</param>
    ///<paramname="Fields">要导出的字段</param>
    ///<paramname="HeadName">字段对应显示的名称</param>
    publicstaticvoidExportToExcel(IListdataList,string[]fields,string[]headTexts)
    {
      ExportToExcel(dataList,fields,headTexts,string.Empty);
    }
    ///<summary>
    ///设置样式
    ///</summary>
    ///<paramname="gvw"></param>
    privatestaticvoidSetStype(GridViewgvw)
    {
      gvw.Font.Name="Verdana";
      gvw.BorderStyle=System.Web.UI.WebControls.BorderStyle.Solid;
      gvw.HeaderStyle.BackColor=System.Drawing.Color.LightCyan;
      gvw.HeaderStyle.ForeColor=System.Drawing.Color.Black;
      gvw.HeaderStyle.HorizontalAlign=System.Web.UI.WebControls.HorizontalAlign.Center;
      gvw.HeaderStyle.Wrap=false;
      gvw.HeaderStyle.Font.Bold=true;
      gvw.HeaderStyle.Font.Size=10;
      gvw.RowStyle.Font.Size=10;
    }
    ///<summary>
    ///导出GridView中的数据到Excel
    ///</summary>
    ///<paramname="gvw"></param>
    ///<paramname="DataList"></param>
    publicstaticvoidExportToExcel(GridViewgvw,stringtitle)
    {
      stringfileName;
      HttpContext.Current.Response.Buffer=true;
      HttpContext.Current.Response.ClearContent();
      HttpContext.Current.Response.ClearHeaders();
      fileName=string.Format("xhmd{0:yyMMddHHmm}.xls",DateTime.Now);
      HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename="+fileName);
      HttpContext.Current.Response.ContentType="application/vnd.ms-excel";
      StringWritertw=newSystem.IO.StringWriter();
      HtmlTextWriterhw=newSystem.Web.UI.HtmlTextWriter(tw);
      gvw.RenderControl(hw);
      if(!string.IsNullOrEmpty(title))
      {
        HttpContext.Current.Response.Write("<b><center><fontsize=3face=Verdanacolor=#0000FF>"+title+"</font></center></b>");
      }
      HttpContext.Current.Response.Write(tw.ToString());
      HttpContext.Current.Response.Flush();
      HttpContext.Current.Response.Close();
      HttpContext.Current.Response.End();
      gvw.Dispose();
      tw.Dispose();
      hw.Dispose();
      gvw=null;
      tw=null;
      hw=null;
    }
    publicstaticvoidDataTable2Excel(System.Data.DataTabledtData)
    {
      System.Web.UI.WebControls.DataGriddgExport=null;
     //当前对话
      System.Web.HttpContextcurContext=System.Web.HttpContext.Current;
      //IO用于导出并返回excel文件
      System.IO.StringWriterstrWriter=null;
      System.Web.UI.HtmlTextWriterhtmlWriter=null;
      if(dtData!=null)
     {
        //设置编码和附件格式
       curContext.Response.ContentType="application/vnd.ms-excel";
       curContext.Response.ContentEncoding=System.Text.Encoding.UTF8;
       curContext.Response.Charset="";
        
        //导出excel文件
       strWriter=newSystem.IO.StringWriter();
       htmlWriter=newSystem.Web.UI.HtmlTextWriter(strWriter);
       //为了解决dgData中可能进行了分页的情况,需要重新定义一个无分页的DataGrid
        dgExport=newSystem.Web.UI.WebControls.DataGrid();
        dgExport.DataSource=dtData.DefaultView;
        dgExport.AllowPaging=false;
        dgExport.DataBind();
        //返回客户端
        dgExport.RenderControl(htmlWriter);  
        curContext.Response.Write(strWriter.ToString());
        curContext.Response.End();
      }
    }
  }

相关文章

  • IIS上部署Asp.net core Webapi的实现步骤

    IIS上部署Asp.net core Webapi的实现步骤

    ASP.NET Core Web API是构建RESTful应用程序的理想平台,本文主要介绍了IIS上部署Asp.net core Webapi的实现步骤,具有一定的参考价值,感兴趣的可以了解一下
    2024-07-07
  • 在ASP.NET中,设置Session的过期时间的方法

    在ASP.NET中,设置Session的过期时间的方法

    在ASP.NET中,设置Session的过期时间的方法,需要的朋友可以参考下
    2012-12-12
  • ASP.NET WebAPI2复杂请求跨域设置的方法介绍

    ASP.NET WebAPI2复杂请求跨域设置的方法介绍

    这篇文章主要给大家介绍了关于ASP.NET WebAPI2复杂请求跨域设置的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者使用ASP.NET具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
    2020-07-07
  • C#中遍历各类数据集合的方法总结

    C#中遍历各类数据集合的方法总结

    C#中遍历各类数据集合的方法,这里自己做下总结:枚举类型、遍历ArrayList(Queue、Stack)、Winform窗体中的控件、HashTable哈希表等等,具体祥看下文
    2013-05-05
  • ASP.NET MVC5网站开发修改及删除文章(十)

    ASP.NET MVC5网站开发修改及删除文章(十)

    这篇文章主要为大家详细介绍了ASP.NET MVC5网站开发修改及删除文章,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2015-09-09
  • 写一个含数字,拼音,汉字的验证码生成类

    写一个含数字,拼音,汉字的验证码生成类

    本文和大家分享的是一个集成1:小写拼音;2:大写拼音;3:数字;4:汉字的验证码生成类。本章例子也会有一个mvc使用验证码校验的场景。具有一定的参考价值,下面跟着小编一起来看下吧
    2017-01-01
  • ASP.NET 清除模式窗口数据缓存的操作方式

    ASP.NET 清除模式窗口数据缓存的操作方式

    模式窗口showModalDialog()弹出页面在asp.net中经常用到,接下来为大家介绍下清除模式窗口缓存数据的问题
    2013-04-04
  • 拥有网页版小U盘 ASP.NET实现文件上传与下载功能

    拥有网页版小U盘 ASP.NET实现文件上传与下载功能

    这篇文章主要为大家详细介绍了ASP.NET实现文件上传与下载功能,类似于U盘功能,具有一定的参考价值。感兴趣的小伙伴们可以参考一下
    2016-08-08
  • asp.net session丢失的解决方法小结

    asp.net session丢失的解决方法小结

    正常操作情况下会有ASP.NET Session丢失的情况出现。因为程序是在不停的被操作,排除Session超时的可能。另外,Session超时时间被设定成60分钟,不会这么快就超时的。
    2011-02-02
  • .Net使用Xunit工具进行单元测试

    .Net使用Xunit工具进行单元测试

    这篇文章介绍了.Net使用Xunit工具进行单元测试的方法,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-06-06

最新评论