blog

Home / DeveloperSection / Blogs / ASP.Net 2.0: Export GridView to Excel

ASP.Net 2.0: Export GridView to Excel

AVADHESH PATEL4693 31-Aug-2012

The focus of the article is the Export to Excel functionality - the Gridview and its data binding are only for demonstrating the Export functionality.

For exporting GridView to excel, take a gridveiw in asp.net page and bind gridview to a database for display records. Take a button and write bellow code on button’s click.

When you execute the webpage, gridview and button will be display.  When you click the button “Export.xml” file downloaded on your system. This file have the data which display in gridview.

            //Clears all content output from the buffer stream
            Response.ClearContent();
            //to pop a 'open/save file' dialog for the users, so that they can download an file on to their local machines
            Response.AddHeader("content-disposition", "attachment; filename=Export.xls");
            //A string describing the content type. This string is usually formatted as type/subtype,
            //where type is the general content category, and subtype is the specific content type.
            Response.ContentType = "application/ms-excel";
            //StringWriter is used with HtmlTextWriter.
            StringWriter sw = new StringWriter();
            //HtmlTextWriter writes HTML programmatically. It allows you to generate a list of HTML elements, such as <div> elements.
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            //The HtmlForm control is a container for server controls on a Web Forms page.
            HtmlForm frm = new HtmlForm();
            GridView1.Parent.Controls.Add(frm);
            frm.Attributes["runat"] = "server";
            frm.Controls.Add(GridView1);
            frm.RenderControl(htw);
            Response.Write(sw.ToString());
            Response.End();

Updated 18-Sep-2014
Avadhesh Kumar Patel District Project Manager - Aligarh 14 months work experience in Panchayati Raj Department Sector as District Project Manager & 12 months work experience in IT Sector as Software Engineer. :-)

Leave Comment

Comments

Liked By