GridView中导出表格的代码


在GridView中还是经常会遇到导出Excel,现在把导出gridView数据代码记录下来,仅供参考 如果有更好的方法,也可以交流

一、先建一个类,其中的一个方法为ToExcel。代码如下

 public static void ToExcel(Control ctl, string FileName)
    {
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.ClearHeaders();
        HttpContext.Current.Response.Buffer = true;
        HttpContext.Current.Response.Charset = System.Text.Encoding.Default.HeaderName;
        //HttpContext.Current.Response.Charset = "Unicode";
        //HttpContext.Current.Response.Charset = "gb2312";
        HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;
        HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
        HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls");
        ctl.Page.EnableViewState = false;
        System.IO.StringWriter tw = new System.IO.StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(tw);
        ctl.RenderControl(hw);
        HttpContext.Current.Response.Write("<meta http-equiv=Content-Type content=\"text/html; charset=gb2312\">");
        //HttpContext.Current.Response.Write("<html><head><meta http-equiv=Content-Type content=\"text/html; charset=gb2312\"></head>");
        HttpContext.Current.Response.Write(tw.ToString());
        //HttpContext.Current.Response.Write("</body></html>"); 
        HttpContext.Current.Response.Flush();
        HttpContext.Current.Response.End();
    }

二、在含有Gridview中的页面中后台代码引用

2.1引用前要在前台代码头文件中把  EnableEventValidation="false" 设置一下

2.2在后台开始引用

一个是button按钮事件(ps:其中GvFloorList为GridView的ID)


 protected void btnExcel_Click(object sender, EventArgs e)
    {
        if (this.GvFloorList.Rows.Count > 0)
        {
            int page = this.GvFloorList.PageIndex;
            this.GvFloorList.AllowPaging = false;
            this.GvFloorList.AllowSorting = false;

            BindData();

            Common.ToExcel(GvFloorList, "表格名");
            this.GvFloorList.AllowPaging = true;
            this.GvFloorList.AllowSorting = true;

            BindData();
            this.GvFloorList.PageIndex = page;
        }
    }

还有一个是要在后台代码中添加一个继承方法

    #region VerifyRenderingInServerForm
    /// <summary>
    /// VerifyRenderingInServerForm
    /// </summary>
    /// <param name="control"></param>
    public override void VerifyRenderingInServerForm(Control control)
    {
        //base.VerifyRenderingInServerForm(control);  
    }
    #endregion



 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值