EXPORT A DATA FROM GRIDVIEW TO EXCEL USING C#
excel.aspx
excel.aspx.cs
<%@ 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>
<asp:GridView ID="gvDetails"
AutoGenerateColumns="false"
CellPadding="5"
runat="server">
<Columns>
<asp:BoundField HeaderText="UserId"
DataField="UserId"
/>
<asp:BoundField HeaderText="UserName"
DataField="UserName"
/>
<asp:BoundField HeaderText="Education"
DataField="Education"
/>
<asp:BoundField HeaderText="Location"
DataField="Location"
/>
</Columns>
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
</asp:GridView>
</div>
<asp:Button ID="btnExport"
runat="server"
Text="Export to
Excel"
onclick="btnExport_Click" />
</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.IO;
using
System.Data;
public partial class excel : System.Web.UI.Page
{
protected void Page_Load(object
sender, EventArgs e)
{
if
(!IsPostBack)
{
BindGridview();
}
}
protected void BindGridview()
{
DataTable
dt = new DataTable();
dt.Columns.Add("UserId",
typeof(Int32));
dt.Columns.Add("UserName",
typeof(string));
dt.Columns.Add("Education",
typeof(string));
dt.Columns.Add("Location",
typeof(string));
dt.Rows.Add(1, "SureshDasari",
"B.Tech", "Chennai");
dt.Rows.Add(2, "MadhavSai",
"MBA", "Nagpur");
dt.Rows.Add(3, "MaheshDasari",
"B.Tech", "Nuzividu");
dt.Rows.Add(4, "Rohini",
"MSC", "Chennai");
dt.Rows.Add(5, "Mahendra",
"CA", "Guntur");
dt.Rows.Add(6, "Honey",
"B.Tech", "Nagpur");
gvDetails.DataSource = dt;
gvDetails.DataBind();
}
public override void
VerifyRenderingInServerForm(Control control)
{
/* Verifies
that the control is rendered */
}
protected void btnExport_Click(object
sender, EventArgs e)
{
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment;
filename={0}", "Customers.xls"));
Response.ContentType = "application/ms-excel";
StringWriter
sw = new StringWriter();
HtmlTextWriter
htw = new HtmlTextWriter(sw);
gvDetails.AllowPaging = false;
BindGridview();
//Change the
Header Row back to white color
gvDetails.HeaderRow.Style.Add("background-color", "#FFFFFF");
//Applying
stlye to gridview header cells
for (int i = 0; i < gvDetails.HeaderRow.Cells.Count;
i++)
{
gvDetails.HeaderRow.Cells[i].Style.Add("background-color",
"#df5015");
}
gvDetails.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
}
Download Source Code:expoetexcelfromgridview