2010-08-06

GridView export to Excel

   public static void GVExportExcel(HttpContext c, GridView GV,string FileName )
    {
        System.IO.StringWriter tw = new System.IO.StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(tw);       
        c.Response.ContentType = "application/x-excel";
        c.Response.AddHeader("content-disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName + ".xls"));
        GV.RenderControl(hw);
        c.Response.Write(tw.ToString());
        c.Response.End();
    }
Notification :
1. If page is under MasterPage, it requires to add EnableEventValidation="false" inside <%@ Page %>
2. If page is in inside UpdatePanel, it requires to register postback control. ScriptManager.GetCurrent(Page).RegisterPostBackControl(btnExport);
3. Following override function is required inside page.
    public override void VerifyRenderingInServerForm(Control control)
    {
        //For GridView export Excel
        /* Confirms that an HtmlForm control is rendered for the specified ASP.NET
        server control at run time. */
    }

沒有留言:

張貼留言