Sunday, March 23, 2014

Export Data from Gridview to Excel in ASP.NET using C#

Here I will like to explain how to export data from Gridview control to Excel file in ASP.NET using C# programming language.

Following is code we need to write for export data from gridview to excel



<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Export Excel in Asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<asp:Button ID="btnExport" runat="server" Text="Export to Excel"
onclick="btnExportExcel_Click" />
<div>
<asp:GridView ID="gvUserInfo" AutoGenerateColumns="false" CellPadding="8" runat="server">
<Columns>
<asp:BoundField HeaderText="UserId" DataField="UserId" />
<asp:BoundField HeaderText="First Name" DataField="First Name" />
<asp:BoundField HeaderText="Last Name" DataField="Last Name" />
<asp:BoundField HeaderText="Address" DataField="Address" />
</Columns>
<HeaderStyle BackColor="#4381FD" Font-Bold="true" ForeColor="#FFFFFF" />
</asp:GridView>
</div>

</form>
</body>
</html>

Now in code behind add following code



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("First Name", typeof(string));
dt.Columns.Add("Last Name", typeof(string));
dt.Columns.Add("Address", typeof(string));
dt.Rows.Add(1, "Vibhav", "Bhavsar", "Gujarat");
dt.Rows.Add(2, "Mahesh", "patel", "Pune");
dt.Rows.Add(3, "Geeta", "shah", "Chennai");
dt.Rows.Add(4, "Meet", "Rathod", "Nagpur");
dt.Rows.Add(5, "Akshay", "Trivedi", "Mumbai");
gvDetails.DataSource = dt;
gvDetails.DataBind();
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
protected void btnExportExcel_Click(object sender, EventArgs e)
{
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment;filename= UserList.xls");
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gvDetails.AllowPaging = false;
BindGridview();
//Header Row back to white color
gvDetails.HeaderRow.Style.Add("background-color", "#FFFFFF");
//gridview header cells
for (int i = 0; i < gvDetails.HeaderRow.Cells.Count; i++)
{
gvDetails.HeaderRow.Cells[i].Style.Add("background-color", "#4384FD");
}
gvDetails.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}

Whenever we run application in ASP.NET we will see the screen like as below



Once we click on Export to Excel button we will see data in excel file like as below


No comments:

Post a Comment