Pages

Men

rh

7/09/2012

Export to Excel from Grid in C#

    
protected void BtnExportToExcel_Click(object sender, EventArgs e)
    {
        Response.Clear();
        Response.AddHeader("content-disposition", "attachment;filename=ReversalExcel.xls");
        Response.Charset = "";
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = "application/vnd.xls";
        System.IO.StringWriter stringWrite = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
        dgSearchReversal.RenderControl(htmlWrite);
        Response.Write(stringWrite.ToString());
        Response.End();
    }

   dgSearchReversal is the Grid view name.

  we need to add below code also in the Same page to eliminate the error.
 That is Grid view must be placed inside form tag runat ="server"
 

  public override void VerifyRenderingInServerForm(Control control)
    {
        /* Confirms that an HtmlForm control is rendered for the specified ASP.NET
           server control at run time. */
    }

No comments :

Post a Comment