Export data from gridview to excel in C#

//additional references to import  
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;
 
   public static void Export_Excel(HttpResponse Response, GridView grid)
    {
        string filename = DateTime.Now.ToString("0:yyyyMMddhhmmss") + ".xls";
        Response.ClearContent();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", "attachment; filename=" + filename);
        Response.Charset = "";
        Response.ContentType = "application/vnd.ms-excel";
        grid.AllowPaging = false;
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        HtmlForm frm = new HtmlForm();
        grid.Parent.Controls.Add(frm);
        frm.Attributes["runat"] = "server";
        frm.Controls.Add(grid);
        frm.RenderControl(htw);
        Response.Write(sw.ToString());
        Response.Flush();
        Response.End();
    }

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.