Exporting Grid view or Div to Excel in Asp.net using C#.net

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="excel.aspx.cs" Inherits="excel" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div id="div" runat="server"> <asp:Button ID="btnExport" runat="server" Text="Export" OnClick="btnExport_Click" /> <div runat="server" id="divexport"> <h1 style="color: Green"> Export to excel sample...</h1> <asp:GridView ID="gv" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None"> <AlternatingRowStyle BackColor="White" /> <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" /> <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" /> <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" /> <RowStyle BackColor="#FFFBD6" ForeColor="#333333" /> <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" /> <SortedAscendingCellStyle BackColor="#FDF5AC" /> <SortedAscendingHeaderStyle BackColor="#4D0000" /> <SortedDescendingCellStyle BackColor="#FCF6C0" /> <SortedDescendingHeaderStyle BackColor="#820000" /> </asp:GridView> </div> </div> </form> </body> </html>

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; public partial class excel : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { bindGrid(); } } public void bindGrid() { DataTable dt = new DataTable(); dt.Columns.Add("SNO"); dt.Columns.Add("Department"); dt.Columns.Add("EmpName"); dt.Columns.Add("EmpNo"); dt.Columns.Add("Location"); dt.Columns.Add("Designation"); for (int i = 0; i < 10; i++) { DataRow dr = dt.NewRow(); dr["SNO"] = i; dr["Department"] = "Department-" + i; dr["EmpName"] = "EmpName-" + i; dr["EmpNo"] = "EmpNo-" + i; dr["Location"] = "Location-" + i; dr["Designation"] = "Designation-" + i; dt.Rows.Add(dr); dt.AcceptChanges(); } gv.DataSource = dt; gv.DataBind(); } protected void btnExport_Click(object sender, EventArgs e) { Response.Clear(); Response.AddHeader("content-disposition", "attachment;filename=FileName.xls"); Response.Charset = ""; Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.ContentType = "application/vnd.xls"; System.IO.StringWriter stringWrite = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite); divexport.RenderControl(htmlWrite); Response.Write(stringWrite.ToString()); Response.End(); } //don’t forget to add this method , other wise we will get Control gv of type //'GridView' must be placed inside a form tag with runat=server. public override void VerifyRenderingInServerForm(Control control) { } }