|
|
|
|
|
|
Author Rank:
|
|
Total page views :
236678
|
|
Total downloads :
|
|
|
|
|
|
Similar ArticlesMost ReadTop RatedLatest
|
|
|
|
|
|
|
|
|
|
Export to Excel is one of the most common functionality required in ASP.Net pages. Users can download the data from the datagrid into an Excel spreadsheet for offline verification and/or computation. This article includes the source code for such functionality.
How it works
This main functionality to Export a datagrid from an ASP.Net Web Form to an Excel format is actually very simple. There are several solutions for this implementation and in this example we will convert the datagrid to excel format by manipulating the MIME type (media type or Content Type) of the Response. The RenderControl method available in the .Net Framework provides the server control content to an HtmlTextWriter which is subsequently written out to the Response Stream.
private void Button1_Click(object sender, System.EventArgs e) { //export to excel Response.Clear(); Response.Buffer= true; Response.ContentType = "application/vnd.ms-excel"; Response.Charset = ""; this.EnableViewState = false; System.IO.StringWriter oStringWriter = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter); this.ClearControls(dg); dg.RenderControl(oHtmlTextWriter); Response.Write(oStringWriter.ToString()); Response.End(); }
Code Listing : Output the contents of the datagrid to Excel spreadsheet
And just one more detail
There's just one thing to take care of. A run-time error occurs if the DataGrid contains any controls other than the LiteralControl. This means that enabling Sorting, Paging or adding Template Columnns or Button columns to the datagrid can cause an error. There are several approaches to workaround this limitation. We will remove all the non-Literal controls in the DataGrid and replace the controls with a text representation , where possible. To do so, we will make use of Reflection. instead of querying each type of control and working out a replacement.
For all controls that have a SelectedItem property, we replace the control with the literal value of the SelectedItem property of the control. This covers most lists. For all controls that have a Text property, we replace the control with the literal value of the Text property of the control. This covers TextBox, Buttons, Button Columns, TemplateColumns. We make an exception only for TableCell controls. This takes care of most of the cases and you can add more checks and balances as required. The only drawback for this generalised formula is the order of the controls within a single cell could get changed.
private void ClearControls(Control control) { for (int i=control.Controls.Count -1; i>=0; i--) { ClearControls(control.Controls[i]); } if (!(control is TableCell)) { if (control.GetType().GetProperty("SelectedItem") != null) { LiteralControl literal = new LiteralControl(); control.Parent.Controls.Add(literal); try {literal.Text = (string)control.GetType().GetProperty("SelectedItem").GetValue(control,null); } catch { } control.Parent.Controls.Remove(control); } else if (control.GetType().GetProperty("Text") != null) { LiteralControl literal = new LiteralControl(); control.Parent.Controls.Add(literal); literal.Text = (string)control.GetType().GetProperty("Text").GetValue(control,null); control.Parent.Controls.Remove(control); } } return; }
Code Listing : Output the contents of the datagrid to Excel spreadsheet
In our sample web form, we connect to the Sample Pubs SQL Server database and display the data from the Employees table. The sample datagrid uses paging and a dummy Edit Column.
Complete Code Listing
<%@ Page language="C#" Debug="true" %> <%@ Import Namespace="System.Drawing" %> <%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.SqlClient" %>
<script Language="C#" runat="server"> private void Button1_Click(object sender, System.EventArgs e) { //export to excel Response.Clear(); Response.Buffer= true; Response.ContentType = "application/vnd.ms-excel"; Response.Charset = ""; this.EnableViewState = false; System.IO.StringWriter oStringWriter = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter); this.ClearControls(dg); dg.RenderControl(oHtmlTextWriter); Response.Write(oStringWriter.ToString()); Response.End(); } private void Page_Load(object sender, System.EventArgs e) { if (!IsPostBack) { SqlConnection conn = new SqlConnection ("data source=(local);initial catalog=Northwind;Pwd=p@ssw0rd;User ID=sa"); SqlCommand cmd = new SqlCommand ("Select LastName, FirstName, Title, TitleOfCourtesy, BirthDate, HireDate, Address, City, Region, PostalCode, Country from Employees", conn); SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds); dg.DataSource = ds.Tables[0]; dg.DataBind(); } } private void ClearControls(Control control) { for (int i=control.Controls.Count -1; i>=0; i--) { ClearControls(control.Controls[i]); } if (!(control is TableCell)) { if (control.GetType().GetProperty("SelectedItem") != null) { LiteralControl literal = new LiteralControl(); control.Parent.Controls.Add(literal); try { literal.Text = (string)control.GetType().GetProperty("SelectedItem").GetValuecontrol,null); } catch { } control.Parent.Controls.Remove(control); } else if (control.GetType().GetProperty("Text") != null) { LiteralControl literal = new LiteralControl(); control.Parent.Controls.Add(literal); literal.Text = (string)control.GetType().GetProperty("Text").GetValue(control,null); control.Parent.Controls.Remove(control); } } return; } </script> <html> <body leftmargin="0" topmargin="0" marginwidth="0" marginheight="0"> <form id="frm" runat="server"> <asp:Button id="Button1" runat="server" Text="Export to Excel" OnClick="Button1_Click"></asp:Button><BR> <asp:Datagrid id="dg" runat="server" AutoGenerateColumns="True" AllowSorting="true" AllowPaging="true"CellPadding="3" PageSize=3> <columns> <asp:TemplateColumn> <ItemTemplate> <asp:LinkButton runat="server" CommandName="Edit"CausesValidation="false" ID="btnView"Text="Edit"/> </ItemTemplate> </asp:TemplateColumn> </columns> </asp:datagrid> <BR> </form> </body> </html>
Note that you will need to have Excel 97 or later installed on the client. You can also add extra code for formatting the excel output.
NOTE: This article is purely for educational purpose. This article should not be construed as a best practices white paper. This article is entirely original, unless specified. Any resemblance to other material is an un-intentional coincidence and should not be misconstrued as malicious, slanderous, or any anything else hereof.
|
|
|
Login
to add your contents and source code to this article
|
|
|
|
|
|
|
|
|
|
Dipal Choksi
Dipal Choksi has over 10 years of industry experience in team-effort projects and also as an individual contributor. She has been working on the .Net platform since the beta releases of .Net 1.0.
|
|
|
|
|
|
|
|
|
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional
consulting company, our consultants are well-known experts in .NET and many of them
are MVPs, authors, and trainers. We specialize in Microsoft .NET development and
utilize Agile Development and Extreme Programming practices to provide fast pace
quick turnaround results. Our software development model is a mix of Agile Development,
traditional SDLC, and Waterfall models.
|
|
Click here to learn more about C# Consulting. |
|
|
|
|
|
|
|
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon.
Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees.
As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
|
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
|
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
|
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today. With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications. Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
|
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or
application via a range of API's. Learn More about our API connections.
|
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
|
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
|
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|