将GridView数据导出到Excel实现

最近想整理一些词库,懒得手动找,又怕手一哆嗦有遗漏,决定写程序完成吧。

首先将数据用GridView控件显示到页面上,效果如下:

 

接下来将GridView中的内容导出到Excel,方法如下:

 

  ///   <summary>
    
///  由GridView导出Excel
    
///   </summary>
    
///   <param name="ctl"> GridView控件ID </param>
    
///   <param name="FileName"> 导出Excel名称 </param>
     private   void  ToExcel(Control ctl,  string  FileName)
    {
        HttpContext.Current.Response.Charset 
=   " UTF-8 " ;
        HttpContext.Current.Response.ContentEncoding 
=  System.Text.Encoding.UTF8;
        HttpContext.Current.Response.ContentType 
=   " application/ms-excel " ;
        HttpContext.Current.Response.AppendHeader(
" Content-Disposition " " attachment;filename= "   +   ""   +  FileName);
        ctl.Page.EnableViewState 
=   false ;
        System.IO.StringWriter tw 
=   new  System.IO.StringWriter();
        HtmlTextWriter hw 
=   new  HtmlTextWriter(tw);
        ctl.RenderControl(hw);
        HttpContext.Current.Response.Write(tw.ToString());
        HttpContext.Current.Response.End();
    }

 

 

在按钮上添加事件来导出Excel。注意,因为GridView是有分页和排序设置的,为了能够显示完整的数据,要先取消分页排序,导出之后再恢复设置。代码如下:

 

   protected   void  btnExport_Click( object  sender, EventArgs e)
    {
        gvWord.AllowPaging 
=   false ;
        gvWord.AllowSorting 
=   false ;
        Display();
        ToExcel(gvWord, 
" word.xls " );
        gvWord.AllowSorting 
=   true ;
        gvWord.AllowPaging 
=   true ;
        Display();
    }

 

 

可是运行之后报错:

类型“GridView”的控件“GridView1”必须放在具有 runat=server 的窗体标记内。

 

添加重写方法:

 

  public   override   void  VerifyRenderingInServerForm(Control control)
    {
        
// base.VerifyRenderingInServerForm(control);
    }

 

 

完成后效果如下:

 

这下可以让程序帮我整理了,省了一笔麻烦啊。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值