Gridview导出为Excel

1.由于gridview的内容可能是分页显示的,因此,这里在每次导出excel时,先将gridview的allowpaging属性设置为false,然后databind()一下,确保搂到所有数据;
2.不用单独设置导出的路径,导出时会弹出对话框让你确认保存位置;
3.要写一个空的VerifyRenderingInServerForm方法(必须写),以确认在运行时为指定的ASP.NET 服务器控件呈现HtmlForm 控件;
4.导出后别忘记再重新设置其allowpaging属性;
   当我把这些都设置好以后,点击[导出],出现了 只能在执行 Render() 的过程中调用 RegisterForEventValidation(RegisterForEventValidation can only be called during Render(); ) 的错误,又检查代码,没发现问题啊,搞了一会弄不出来,然后搜索了一下,发现了解决办法:
修改你的aspx文件中的:
<%@ Page Language="C#" EnableEventValidation = "false" AutoEventWireup="true" CodeFile="SysUser.aspx.cs" Inherits="Autho_SysUser2" %>
增加红色的部分就ok了。
下面是代码和截图:
    #region 导出为Excel
    public override void VerifyRenderingInServerForm(Control control)
    {
        // Confirms that an HtmlForm control is rendered for
    }

    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();
    }

    private void toExcelClk()
    {
        gvSysUser.AllowPaging = false;
        gvSysUser.AllowSorting = false;
        gvSysUser.DataBind();
        ToExcel(gvSysUser, "OFS_Data.xls");
        gvSysUser.AllowPaging = true;
        gvSysUser.AllowSorting = true;
        gvSysUser.DataBind();
    }

    #endregion



posted on 2009-11-26 15:03  不悔的青春  阅读(277)  评论(0编辑  收藏  举报

导航