Creating a Simple ASP.NET Report with Export to Excel
page 4 of 5
by Steven Smith
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 36110/ 56

Export Report to Excel in ASP.NET

In order to export to Excel, we need two things:

1. Some way to tell the page to switch into Excel rendering mode (or a different page that only serves Excel).

2. Some way for the page to tell the browser that the content should be interpreted as an Excel sheet.

The simplest way to achieve the first requirement is to add a link to the page that says "Export to Excel" and simply links back to the same page but adds a querystring parameter, like this:

It's not strictly required that this link have an id or a runat="server" but this is useful if we want to avoid displaying this link in our Excel report.  With this in place, we can add a simple check to the Page_Load() method in the codebehind to determine whether we should render Excel:

Now, finally, we get to the good part.  How do we convert our simple HTML table into an Excel worksheet?  The cool thing is, we don't have to worry about that.  Excel takes care of that for us, by automatically converting HTML (and in particular, tables) into Excel's columns and rows format.  All we need to do is tell the browser that we want Excel to handle this request, and provide a few clues like what the resulting download should be named.  We'll also use this opportunity to hide some HTML-only elements on the page, like the Export to Excel link.  The resulting RenderExcel() method looks like this:

Whatever filename you specify is what the user will be prompted to download, like so:

Excel may warn that the file you are opening is in a different format than the extension (in this case, it's HTML even though we told Excel it was an xls file).  You can simply ignore this prompt, resulting in Excel opening the file with results like this:


View Entire Article

User Comments

Title: eeqw   
Name: qwrqwr
Date: 2012-11-01 7:42:16 AM
Title: dsf   
Name: sdfsd
Date: 2012-04-26 11:17:52 PM
Title: MVC3   
Name: Tony
Date: 2011-06-03 5:22:59 PM
Nice article, thank you. I used it with mvc3, it works!
Title: ASP.NET   
Name: 5th edition,
Date: 2011-05-27 10:04:06 AM
this new book was delivered..
Title: .net 3.5 version needed   
Name: windy
Date: 2011-05-13 8:27:06 AM
do the needful.
Title: hi   
Name: hassan humayun
Date: 2011-05-11 8:32:25 AM
nice article , but tell me one thing if the user doest have office installed on his system then what will happen, would it throw an exception.

Community Advice: ASP | SQL | XML | Regular Expressions | Windows

©Copyright 1998-2024  |  Page Processed at 2024-05-22 7:08:46 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search