Saturday 28 April 2012

Export To excel from gridview


   protected void btnGenerate_Click(object sender, EventArgs e)
        {
            // Here is example code for export Gridview to excel sheet,

            Response.Clear();             // Clear the response
            // Set the type and filename
            Response.AddHeader("content-disposition", "attachment;filename =        
                                 NameofSheet.xls"
);
            Response.Charset = "";
            Response.ContentType = "application/ms-excel";
      
       // Add the HTML from the GridView to a StringWriter so we can write it out later 
     
            System.IO.StringWriter sw = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(sw);
            GridView.RenderControl(hw);

            // Write out the data 
            Response.Write(sw.ToString());
            Response.End();

        }

        public override void VerifyRenderingInServerForm(Control control)
        {
            base.VerifyRenderingInServerForm(control);
        }

        //Enjoy Life as much as you can….

No comments:

Post a Comment