Introduction:
In this article, we will see how to Export an ASP.Net 2.0 GridView to Excel.
The focus of the article is the Export to Excel functionality - the Gridview and it's data binding are only for demonstrating the Export functionality.
The code fragments for the Export to Excel functionality below are not linked to the backend structure and can be re-used across projects for the common functionality provided.
Step 1: Setup your web page with the Gridview
In this article, we will assume you are starting with a web page which holds a GridView named GridView1. The GridView in our demo code is bound to a table named "ContactPhone" in a SQL Express database. The following code which exports the databound GridView to Excel is not dependent on the specific databindings and can be used without changes for your scenario.
ContactPhone Table Structure:
Column Name
|
Type
|
ContactID
|
Int (Identity)
|
FName
|
Varchar(50)
|
LName
|
Varchar(50)
|
ContactPhone
|
Varchar(20)
|
Step: The Actual Export
The code to do the Excel Export is very straightforward. You can also export to different application type by changing the content-disposition and ContentType.
string attachment = "attachment; filename=Contacts.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
GridView1.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
If you run the code as above, it will result in an HttpException as follows:
Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server."
To avoid this error, add the following code:
public override void VerifyRenderingInServerForm(Control control)
{
}
Step : Convert the contents
If the GridView contains any controls, such as Checkboxes, Dropdownlists, we need to replace the contents with their relevant values. The following recursive function uses Reflection to determine the type of control. The control is deleted in preparation for the Excel export and the relevant value of the control is added.
private void PrepareGridViewForExport(Control gv)
{
LinkButton lb = new LinkButton();
Literal l = new Literal();
string name = String.Empty;
for (int i = 0; i < gv.Controls.Count; i++)
{
if (gv.Controls[i].GetType() == typeof(LinkButton))
{
l.Text = (gv.Controls[i] as LinkButton).Text;
gv.Controls.Remove(gv.Controls[i]);
gv.Controls.AddAt(i, l);
}
else if (gv.Controls[i].GetType() == typeof(DropDownList))
{
l.Text = (gv.Controls[i] as DropDownList).SelectedItem.Text;
gv.Controls.Remove(gv.Controls[i]);
gv.Controls.AddAt(i, l);
}
else if (gv.Controls[i].GetType() == typeof(CheckBox))
{
l.Text = (gv.Controls[i] as CheckBox).Checked? "True" : "False";
gv.Controls.Remove(gv.Controls[i]);
gv.Controls.AddAt(i, l);
}
if (gv.Controls[i].HasControls())
{
PrepareGridViewForExport(gv.Controls[i]);
}
}
Code Listing:
Image: Page Design
Image : Sample in action
Image: Export to Excel button is clicked
Image: GridView contents exported to Excel
ExcelExport.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ExportExcel.aspx.cs"Inherits="DeleteConfirm" %>
<!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>Contacts Listing</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<strong><span style="font-size: small; font-family: Arial; text-decoration: underline">
Contacts Listing
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Export To Excel" /></span></strong><br />
<br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"DataKeyNames="ContactID"
DataSourceID="SqlDataSource1" EmptyDataText="There are no data records to display."style="font-size: small; font-family: Arial" BackColor="White" BorderColor="#DEDFDE"BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Vertical">
<Columns>
<asp:BoundField DataField="ContactID" HeaderText="ContactID" ReadOnly="True"SortExpression="ContactID" Visible="False" />
<asp:BoundField DataField="FName" HeaderText="First Name" SortExpression="FName" />
<asp:BoundField DataField="LName" HeaderText="Last Name" SortExpression="LName" />
<asp:BoundField DataField="ContactPhone" HeaderText="Phone" SortExpression="ContactPhone" />
<asp:TemplateField HeaderText="Favorites">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate></asp:TemplateField>
</Columns>
<FooterStyle BackColor="#CCCC99" />
<RowStyle BackColor="#F7F7DE" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ContactsConnectionString1 %>"
DeleteCommand="DELETE FROM [ContactPhone] WHERE [ContactID] = @ContactID"InsertCommand="INSERT INTO [ContactPhone] ([FName], [LName], [ContactPhone]) VALUES (@FName, @LName, @ContactPhone)"
ProviderName="<%$ ConnectionStrings:ContactsConnectionString1.ProviderName %>"
SelectCommand="SELECT [ContactID], [FName], [LName], [ContactPhone] FROM [ContactPhone]"
UpdateCommand="UPDATE [ContactPhone] SET [FName] = @FName, [LName] = @LName, [ContactPhone] = @ContactPhone WHERE [ContactID] = @ContactID">
<InsertParameters>
<asp:Parameter Name="FName" Type="String" />
<asp:Parameter Name="LName" Type="String" />
<asp:Parameter Name="ContactPhone" Type="String" />
</InsertParameters>
<UpdateParameters>
<asp:Parameter Name="FName" Type="String" />
<asp:Parameter Name="LName" Type="String" />
<asp:Parameter Name="ContactPhone" Type="String" />
<asp:Parameter Name="ContactID" Type="Int32" />
</UpdateParameters>
<DeleteParameters>
<asp:Parameter Name="ContactID" Type="Int32" />
</DeleteParameters>
</asp:SqlDataSource>
<br />
</div>
</form>
</body>
</html>
ExcelExport.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.IO;
public partial class DeleteConfirm : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
//Export the GridView to Excel
PrepareGridViewForExport(GridView1);
ExportGridView();
}
private void ExportGridView()
{
string attachment = "attachment; filename=Contacts.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
GridView1.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
}
private void PrepareGridViewForExport(Control gv)
{
LinkButton lb = new LinkButton();
Literal l = new Literal();
string name = String.Empty;
for (int i = 0; i < gv.Controls.Count; i++)
{
if (gv.Controls[i].GetType() == typeof(LinkButton))
{
l.Text = (gv.Controls[i] as LinkButton).Text;
gv.Controls.Remove(gv.Controls[i]);
gv.Controls.AddAt(i, l);
}
else if (gv.Controls[i].GetType() == typeof(DropDownList))
{
l.Text = (gv.Controls[i] as DropDownList).SelectedItem.Text;
gv.Controls.Remove(gv.Controls[i]);
gv.Controls.AddAt(i, l);
}
else if (gv.Controls[i].GetType() == typeof(CheckBox))
{
l.Text = (gv.Controls[i] as CheckBox).Checked ? "True" : "False";
gv.Controls.Remove(gv.Controls[i]);
gv.Controls.AddAt(i, l);
}
if (gv.Controls[i].HasControls())
{
PrepareGridViewForExport(gv.Controls[i]);
}
}
}
}
Implementation Options:
In quite a few cases, developers face an error in the Export functionality - typically the error message is "RegisterForEventValidation can only be called during Render();".
Our website readers have contributed some good suggestions in the article comments below. I would particularly like to highlight the suggestion by Marianna, who provides an alternative implementation to the VerifyRenderingInServerForm override. This approach is described below:
- Step 1: Implement the Export functionality as described above.
- Step 2: Remove the code to override the VerifyRenderingInServerForm method.
- Step 3: Modify the code for the ExportGridView function as below. The code highlighted in green creates and HtmlForm on the fly, before exporting the gridview, adds the gridview to this new form and renders the form (instead of rendering the gridview in our original implementation)
private void ExportGridView()
{
string attachment = "attachment; filename=Contacts.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
// Create a form to contain the grid
HtmlForm frm = new HtmlForm();
GridView1.Parent.Controls.Add(frm);
frm.Attributes["runat"] = "server";
frm.Controls.Add(GridView1);
frm.RenderControl(htw);
//GridView1.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
This implementation has the advantage that it can be setup as re-usable code in a separate library, without having to override the base class method each time.
C# export GridView to Excel
ReplyDeleteIts great pankaj, will you please provide me .net training me ? ? ? pleas plz reply me
ReplyDeletehttp://dotnetquery4u.blogspot.in/2015/10/dot-net-framework-interview-questions.html
ReplyDeletedot net framework latest interview questions
ReplyDeletehttp://dotnetquery4u.blogspot.in/2015/10/dot-net-framework-interview-questions.html
Really it is an amazing article I had ever read. I hope it will help a lot for all. Can you more read now visit Dot Net Certification Training Institute in Delhi
ReplyDeleteGreat List Thank you for sharing such an impressive and useful post
ReplyDeleteDot Net Online Training Hyderabad
Hi,
ReplyDeleteThanks for sharing the info about .NET Plz keep sharing on...
Thank you...
ReplyDeleteIt is very good and useful .Learned a lot of new things from your post!
Good creation ,thanks for good info .Net Online Training
I am glad to read this. Thank you for this beautiful content, Keep it up. Techavera is the best Video Editing training course in Noida. Visit us For Quality Learning.Thank you
ReplyDeleteNice article . Thank you for this beautiful content, Keep it up. Techavera is the best
ReplyDeletejava training institute in noida
Visit us For Quality Learning.Thank you
great article thanks for sharing ASP.Net blog this is very knowledgeable post
ReplyDelete.Net summer training
Nice and good article.Thanks for sharing this useful information. If you want to learn .Net or dotnet course in online, please visit below site.
ReplyDeletedotnet Online Training, dotnet course, dotnet online training in kurnool, dotnet online training in hyderabad, dotnet online training in bangalore, online courses, online learning, online education, trending courses, best career courses
Thanks for nice information
ReplyDeleteLearn Import Export, Exim Courses, Training Programs, Classes, and Seminars from Experts. Join Now Short Term Export Import Course Classes, Seminars & Training Programs @ Discounted Fees. Best Institute for Export Import Management Training. Export Training , Export Licenses, Export Consultancy, Import Consultancy, International Trade Show, Custom Clearance, Export Import Insurance, International Business Management, best import export courses in India , best institute for import export management , Exim courses in Maharashtra , Exim institute, export business training, Export Import Management Institute, export import training institute, export training services, Export training, IEC License, import and export course , import and export business training in pune, Mumbai
Thanks for nice information
ReplyDeleteLearn Import Export, Exim Courses, Training Programs, Classes, and Seminars from Experts.Export Training,Export Licenses, Export Consultancy, Import Consultancy, International Trade Show, Export Import Insurance, International Business Management,best import export courses in India , best institute for import export management, Exim courses in Maharashtra, export business training, Export Import Management Institute, export import training institute, export training services, Export training, IEC License, import and export course
Thanks for nice information
ReplyDeleteJoin our Import Export Training Management Program course in Pune, Mumbai, and Maharashtra, India.training on export import documentation, export consultancy, Import Consultancy, export business training, import business training program, export classification training, import export training seminars, export training courses, import training classes, best import export training, classes, course, seminar , program
Thanks for nice information
ReplyDeleteJoin our Import Export Training Management Program course in Pune, Mumbai, and Maharashtra, India.training on export import documentation, export consultancy, Import Consultancy, export business training, import business training program, export classification training, import export training seminars, export training courses, import training classes, international trade training in Pune, best import export training, classes, course, seminar , program
very informative blog and useful article thank you for sharing with us , keep posting learn more Technology
ReplyDeleteDot net courae
Nice information thank you,if you want more information please visit our link dot net course
ReplyDeletedot net online training
visual studio training
nice.
ReplyDeletego langaunage training
azure training
java training
salesforce training
This comment has been removed by the author.
ReplyDelete