Exporting The Razor WebGrid To Excel Using OleDb

This article looks at how you can provide your users with the ability to export the contents of a Razor Web Pages WebGrid to an Excel file using OleDb.

My previous article on exporting WebGrids to Excel showed how to "fool" Excel into accepting HTML as a valid format for a worksheet. However, as pointed out ion that article, there are some side-effects that come with that approach. The first is that Excel 2007 or newer will complain that the file extensions doesn't match the format. The warning message is a little unfriendly, and may not be desirable. In addition, you cannot use the generate Excel file as a data source for ODBC or OleDb, which means that it cannot be used for mail merges or for querying programmatically by anything that uses these providers. So this article shows how you can use the JET OleDb provider to generate a real Excel file that will not suffer from any of these shortcomings.

The first thing you need is a grid. It may as well be the same grid as previous articles:

@{
    Page.Title = "Export To Excel";
    var db = Database.Open("Northwind");
    var query = "SELECT CustomerID, CompanyName, ContactName, Address, City, Country, Phone FROM Customers";
    var data = db.Query(query);
    var grid = new WebGrid(data, ajaxUpdateContainerId: "grid");
}
<h1>Export to Excel</h1>
<div id="gridContainer">
    <div id="grid">
        @grid.GetHtml(    
            tableStyle : "table",
            alternatingRowStyle : "alternate",
            headerStyle : "header",
            columns: grid.Columns(
                grid.Column("CustomerID", "ID"),
                grid.Column("CompanyName", "Company Name"),
                grid.Column("ContactName", "Contact Name"),
                grid.Column("Address"),
                grid.Column("City"),
                grid.Column("Country"),
                grid.Column("Phone")
            )
        )
        <img src="/images/excel-icon.png" id="excel" alt="Export to Excel" title="Export to Excel" />
    </div>
</div>

When the user clicks on the image, it should result in the data being downloaded as an Excel file. At the moment, it is just an image, and it appears below the grid. Here's a little bit of jQuery to move the image to the footer area of the grid and to change the cursor when the user hovers over it:

<script type="text/javascript">
    $(function () {
        $('#excel').appendTo($('tfoot tr td')).on('hover', function () {
            $(this).css('cursor', 'pointer');
        });
        $('#excel').on('click', function () {
            $('<iframe src="/GenerateExcel"></iframe>').appendTo('body').hide();
        });
    });
</script>

The jQuery code also adds a handler to the click event of the image. It creates an iframe which it then adds to the body element, and then it makes the display property equal 'none' using the jQuery hide command. The src for the iframe is a file called GenerateExcel.cshtml, which is responsible for creating the Excel file. The hidden iframe technique is a clean way to manage downloads via AJAX without leaving the current page. Adding an iframe dynamically like this effectively "sucks" the HTTP response from the src URL through to the current page. All of this is the same as in the previous article

Here's where things change from the previous article. When you use the JET provider to connect to an Excel 97-2003 file, the file acts as a database, with each worksheet becoming a table. In order to write to a database, you need the receiving table to exist, to first you need to create an Excel file with at least one worksheet with the column names added:

In addition, you must save this as an Excel 97-2003 file (.xls). If you save it with a .xlsx extension, you will not be able to connect to the file using JET. You will need the ACE provider instead, which may not be installed on the hosting server. You should save the file in App_Data.

Now the code for GenerateExcel:

@{
    Layout = null;

    var appData = Server.MapPath("~/App_Data");
    var originalFileName = "Customers.xls";
    var newFileName = string.Format("{0}.xls", Guid.NewGuid().ToString());
    var originalFile = Path.Combine(appData, originalFileName);
    var newFile = Path.Combine(appData, newFileName);
    File.Copy(originalFile, newFile);
    
    var northwind = Database.Open("Northwind");
    var sql = "SELECT CustomerID, CompanyName, ContactName, Address, City, Country, Phone FROM Customers";
    var customers = northwind.Query(sql);
    
    var connString = string.Format(@"Provider=Microsoft.Jet.OleDb.4.0;
                                    Data Source={0}/{1};Extended Properties='Excel 8.0;HDR=Yes;'", 
                                    appData, newFileName);
    var provider = "System.Data.OleDb";

    using (var excel = Database.OpenConnectionString(connString, provider)){
        
        sql = @"INSERT INTO [Sheet1$] (CustomerID, CompanyName, ContactName, Address, City, Country, Phone) 
            VALUES (@0,@1,@2,@3,@4,@5,@6)";
        foreach(var customer in customers){
            excel.Execute(sql,  
                customer.CustomerID, 
                customer.CompanyName, 
                customer.ContactName, 
                customer.Address, 
                customer.City, 
                customer.Country, 
                customer.Phone);
        }
    }

    Response.AddHeader("Content-disposition", "attachment; filename=report.xls");
    Response.ContentType = "application/octet-stream";
    Response.TransmitFile(newFile);
    Response.Flush();
    File.Delete(newFile);
    Response.End();
}

As with any file that is intended to deliver a non-html response, the Layout is set to null to prevent stray HTML being included in the output. The file that you just created and saved in App_Data is copied and saved with a randomly generated name. This copy will be the actual file that is sent back to the user. This is to prevent possible file concurrency problems arising from too many people wanting to generate reports at the same time. The file has to be a physical file on disk in order for the JET provider to be able to establish a connection to it.

Next the data that appears in the WebGrid is obtained from the database. Then a connection string is prepared for the Excel file that you copied. The connection is opened using the Database.OpenConnectionString method overload that takes a provider name. It is also opened within a using statement. This is done to ensure that the connection to the Excel file is closed at a point that you control - i.e. at the end of the using statement block. The connection would ordinarily be closed by the Web Pages runtime at the end of page execution, but you need the connection to be closed earlier than that. It must be closed prior to any attempt to write the file to the browser so that the OleDb process no longer has a lock on the file.

Once the connection is opened, the data from the previous query is inserted into the Excel file using standard SQL. The worksheet name is wrapped in square brackets [ ] and has a dollar sign $ appended to it. Excel requires this. I don't now why. If you miss off the dollar sign, you get an error message about the table (or 'object') not existing. And if you miss out the brackets, you get a syntax error message, so it's best to play along with this requirement.

Once the data has been written to the Excel file, the using statement block reaches its end and the connection is closed behind the scenes. The Content-Disposition value is set to attachment, and the Content-type is set to application/octet-stream. This combination results in the browser offering a choice to the user - save or open, rather than attempting to display the response. The file is written to the response, and then the response is flushed, Once that has happened, the copy of the file that was created specifically for this process is deleted.

The source code for the sample site that accompanies this article is available as a GitHub repo.

 

Date Posted: Monday, January 7, 2013 8:38 PM
Last Updated: Monday, January 7, 2013 8:43 PM
Posted by: Mikesdotnetting
Total Views to date: 8998

8 Comments

Friday, February 1, 2013 9:31 AM - ARul

Nice.....

Saturday, March 2, 2013 1:10 PM - Ariane

Hi, I recreated your scenario explained in this article, but it seems that the JQuery does not do anything on my page. The Excel icon remains just that: an image at the bottom of the grid. Do you have have an idea why that is?

Tuesday, May 27, 2014 7:45 PM - Steve

This is great and working fine but do you happen to have the same example but using the ACE provider instead? Is it as simple as changing the Provider= line or is there more to it?

Wednesday, May 28, 2014 6:40 AM - Mike

@Steve

Yes, it is as simple as changing the connection string. You can find examples for ACE here: http://www.connectionstrings.com/excel/

Tuesday, December 9, 2014 9:05 PM - Gautam

hello mike,

I am logging exceptions in _pageStart.cshtml file

this line
Response.End();

i making an exception.."thread being aborted"..
I commented the line and there was no exception..

The same happens with response.redirect

I did some research and used a boolean false in the response.redirect method and there is no exception being logged.

is using false ok?

And about the response.End()

Wednesday, December 10, 2014 5:16 PM - Mike

@Gautam,

By default, when you call Response.Redirect or Response.End, the ASP.NET framework throws a ThreadAbortedException. If you don't want an exception to be raised, you pass false in to the method.

Wednesday, December 10, 2014 7:21 PM - Gautam

Hello Mike,

when exporting numbers to excel, the excel is giving a green comment(convert this to number).

How and where do I convert string to integer before exporting to excel.

Saturday, December 13, 2014 10:01 PM - Mike

@Gautam,

I have no idea.
Add your comment

If you have any comments to make about this article, please use this form to do so. Make sure that your comment relates specifically to the article above. More general comments can be posted through the form on the Contact page.

Please note, all comments are moderated, and some may not be published. The kind of things that will ensure your comment is deleted without ever seeing the light of day are as follows:

  • Not relevant to the article
  • Gratuitous links to your own site or product
  • Anything abusive or libellous
  • Spam
  • Anything in a language I don't understand including gibberish.

I do not pass email addresses on to spammers, so a valid one will assist me in responding to you personally if required.

Recent Comments

Allen Michaels 12/17/2014 4:37 PM
In response to Cascading DropDownLists with jQuery and ASP.NET
Fantastic thank you so much!...

Emily 12/17/2014 12:36 PM
In response to Parameterized IN clauses with ADO.NET and LINQ
Thanks, very helpful!!!! Can i use this for multiple in's ????? IN (.....) and IN(...) and IN...

sss 12/16/2014 3:06 PM
In response to Solving the Operation Must Use An Updateable Query error
good...

Gjuro 12/15/2014 10:30 PM
In response to Examining the Edit Methods and Edit View
You have one fromr (and it should be from, I suppose). :-)...

Gjuro 12/15/2014 10:27 PM
In response to Adding Search
Hi, thnx for all this C#->VB translations. Yet, the following code block is (slightly) in error it a...

Scot 12/14/2014 1:39 PM
In response to Entity Framework 6 Recipe - Alphabetical Paging In ASP.NET MVC
Thanks,Mike I found solution....

Gjuro 12/13/2014 10:52 PM
In response to Accessing Your Model's Data from a Controller
The article mentions "Creating an Entity Framework Data Model for an ASP.NET MVC Application" (at is...

Samuel 12/13/2014 8:40 AM
In response to Displaying The First n Characters Of Text
I have failed to use the extension because it throws an error that it doesn't recognise the chop be...

Ignas 12/12/2014 5:11 PM
In response to Cleaner Conditional HTML Attributes In Razor Web Pages
Any suggestions for Html Helper elements with HtmlAttributes, when you need to conditionally set it...

Gautam 12/11/2014 8:50 PM
In response to Validation In Razor Web Pages 2
Hi Mike Is this required for V3, non html helper input...