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();

 

Comments

Popular posts from this blog

Display image from byte array in ASP.NET MVC

Convert a color image to black and white image in C#

Export excel and Pdf with Kendo UI MVC c#