Exporting GridView to an excel file is a very common scenario in any web application. Although the code is not difficult to implement but it requires some time and effort. It would be nice to have this functionality in the form of a custom control. Then you only have to drag and drop the control on the form, adjust few properties and that’s it. In this article I will demonstrate how to create such a custom control which can be used in different applications.
Introduction:
Creating a User Control:
I know I said that we are going to implement the server control. Just wait till the end of this article and I promise that I will deliver you a custom control and not a user control.
The first thing you need to do is to create a new user control. The control we are going to implement will contain a single button which when pressed exports the targeted GridView to excel format.
Implementing the Properties:
The export button control will contain two properties.
FileName: The name of the exported file.
GridViewID: The ID of the GridView which we like to export.
Take a look at the properties below:
/* PUBLIC PROPERTIES */ public string FileName { get { return this.fileName; } set { if (!String.IsNullOrEmpty(value)) this.fileName = value; else throw new ArgumentNullException("FileName invalid."); } } public string GridViewID { get { return this.gridViewID; } set { // check for the validity of the data if (!String.IsNullOrEmpty(value)) this.gridViewID = value; else throw new ArgumentNullException("Value cannot be null or empty."); } } |
As, the name suggests PreExport method formats the GridView. This involves disabling some of the controls inside the GridView. These controls include LinkButtons and DropDownLists. Disabling the controls allow us to get the textual value of the control instead of the control itself. Let’s check out the DisableControls method which is called inside PreExport method.
/* This method is responsible for converting the * nested control values into text values */ private void DisableControls(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); } if (gv.Controls[i].HasControls()) { DisableControls(gv.Controls[i]); } } } |
The DisableControls method is a recursive method as it calls itself to make sure all the LinkButton and DropDownList controls are removed from the GridView and their selected value is inserted in the GridView cell.
Exporting GridView to Excel Extensive Study Although GridView Export Button solves the basic task of exporting the GridView content to excel file it’ functionality is limited. I wrote a detailed article about exporting GridView to excel Extensive Study of GridView Export to Excel. In the article I also described the scenario where you can add styles to the GridView columns. I also discussed the errors you might receive while exporting and how you can handle them. |
The last method in this control is the Export method which is used to export the GridView. Take a look at the code below:
private void Export(GridView gv) { string attachment = "attachment; filename= " + FileName; Response.ClearContent(); Response.AddHeader("content-disposition", attachment); Response.ContentType = "application/excel"; StringWriter sw = new StringWriter(); HtmlTextWriter htw = new HtmlTextWriter(sw); gv.RenderControl(htw); Response.Write(sw.ToString()); Response.End(); } |
Publishing the user control as a custom control is very simple task. The ASP.NET 2.0 build architecture allows you to build an assembly for each single page/control. This is good since now we can reuse our user controls in different applications just like server controls. But this is also bad since creating all those assemblies for each single page is a very long process and it takes lot of time. Off course, you will only notice the wait when you are working on big projects consisting of hundreds of pages.
In order to publish the user control to a server control simply right clicks on the website project and select publish. Now, select “Use Fixed Naming and Single File Assemblies”. This will create separate assemblies for every single page including the user control. Once, publish is succeeded simply, go to the bin directory and add the newly created user control assembly to any web application project you want.
Before Using the Export Button:
Before using the GridView export button on your web form please add the following lines in your page code behind.
public override void VerifyRenderingInServerForm(Control control) { } |
Using the Export to GridView Server Control:
Using the control is pretty simple. All you need to do is to add a reference to the created user control assembly and then you can add the control by using the following code.
<%@ Register Namespace="ASP" TagPrefix="ExportButton" Assembly="App_Web_exporttoexcelbutton.ascx.cdcab7d2" %> |
The strange long name you see in the Assembly attribute is the name of the assembly.
<ExportButton:exporttoexcelbutton_ascx ID="MyExportButton" runat="server" GridViewID="GridView1" FileName="MyExcelFile.xls" /> |
Exporting GridView Contained in a Page Inherited from a Master Page:
You can even use the Export Button to export the GridView which is contained in a page inherited from a master page. The only caviar is that you have to find the ID of the GridView. This is not a big task and can be accomplished in less then 10 seconds. When your page runs simply click “View Source” so that you can see the HTML source. Now, you can search for your GridView, if you are using master pages then your GridView ID might look something like this ctl00$ContentPlaceHolder1$GridView1. Simply, put this ID as a value of the GridViewID of the export button and you are done.
<ExportButton:ExportToExcelButton ID="ExportToExcelButton1" GridViewID="ctl00$ContentPlaceHolder1$GridView1" FileName="NewFile.xls" runat="server"> </ExportButton:ExportToExcelButton> |
EnableEventValidation="false" |
The GridView Export Button controls provide an easy way to export the GridView control. The control is accompanied with complete source code and the library which you can add in your toolbox and use it instantly.