Export Grid View Data To Excel - ASP.NET

Some time we need to generate different kind of reports & need to save it in Excel or word Document for Local Reference, Or sending to others. So here I create a code for achieve this task the first one is  conversion data into Excel & second one is for Word Document.

// For pdf converstion we can use third party dll like ITextSharp

 
using System; 
 
public class Class1
{    
    protected void btn_excel_Click(object sender, EventArgs e)
        {
            string attachment = "attachment; filename=myreport.xls";
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.AddHeader("content-disposition", attachment);
            Response.ContentType = "application/ms-excel";
            StringWriter swriter = new StringWriter();
            HtmlTextWriter htmlwriter = new HtmlTextWriter(swriter);
 
            // Create a form to contain the gridview(MyGridView)
            HtmlForm mynewform = new HtmlForm();
            MyGridView.Parent.Controls.Add(mynewform);
            mynewform.Attributes["runat"] = "server";
            mynewform.Controls.Add(MyGridView);
            mynewform.RenderControl(htmlwriter);
            Response.Write(swriter.ToString());
            Response.End();
        }    
}
 
 
Check out Export GridView Data to Word - ASP.NET 

Post a Comment