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



 

posted @ 2011-07-29 11:06  haiziguo  阅读(249)  评论(0编辑  收藏  举报