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
//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();
frm.Attributes["runat"] = "server";