Export GridView to CSV/Excel in C#

Step 1 : Bind GridView

            //This allows you to bind all data of GridView into ExcelSheet
            GridView1.AllowPaging = false;

            GridView1.DataSource = //List Object or DataTable
            GridView1.DataBind();
 

Step 2 : Export GridView To Excel

            HttpContext.Current.Response.ClearContent();

            HttpContext.Current.Response.AddHeader(“content-disposition”, “attachment; filename=”                           + fileName + “.xls”);   // fileNmae = Name of file

            HttpContext.Current.Response.ContentType = “application/excel”;
            System.IO.StringWriter
sw = new System.IO.StringWriter();
            HtmlTextWriter
htw = new HtmlTextWriter(sw);
            GridView1.RenderControl(htw);
            HttpContext
.Current.Response.Write(sw.ToString());
            HttpContext
.Current.Response.End();

 

Leave a Reply

Your email address will not be published. Required fields are marked *