Tuesday, April 23, 2013

Export to Excel from GridView in C#

This sample code will help you export data from GridView to Excel and formatting Excel file in C# . Follow the below process:
    protected void ExportToExcel_Click(object sender, EventArgs e)
    {
        BindgvPDRecovery(); // Bind GridView1
        Response.ClearContent();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Report.xls"));
        Response.ContentType = "application/vnd.xls";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        GridView1.AllowPaging = false; GridView1.DataBind();
        GridView1.HeaderRow.Style.Add("background-color", "#000000");
        GridView1.RenderControl(htw);
        Response.Write(sw.ToString());
        Response.End();
}

If have any query feel free ask me please.
Hope this helps !!

No comments:

Post a Comment