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: 8672

4 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/
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

Gautam 11/20/2014 8:01 AM
In response to I'm Writing A Book On WebMatrix
Hello Mike, I read your book, loved it! However, I have a few request/suggestions: 1) an example...

Bret Dev 11/19/2014 8:39 PM
In response to The Difference Between @Helpers and @Functions In WebMatrix
Excellent post! One concern - where can you place global @Functions code within an MVC project to Is...

Rob Farquharson 11/19/2014 4:28 PM
In response to iTextSharp - Links and Bookmarks
How can I place text at an absolute position on the page? Also, how can I rotate text?...

Andy 11/17/2014 8:08 PM
In response to MVC 5 with EF 6 in Visual Basic - Sorting, Filtering and Paging
Hello I'm testing your sorting instructions above. This is great and I was able to get it to work...

Gautam 11/17/2014 5:51 PM
In response to WebMatrix - Database Helpers for IN Clauses
Hi Mike, I am very new to programming: In the above example if I want to use a delete button the...

donramon 11/17/2014 3:22 PM
In response to Entity Framework 6 Recipe - Alphabetical Paging In ASP.NET MVC
Congratulations on your new website look and the excellent articles. Thank you!...

Gautam 11/17/2014 11:26 AM
In response to Looking At The WebMatrix WebGrid
Hi Mike, I add the jquery script at the end of my html file.. when ajax attribute is added to the be...

Chet Ripley 11/15/2014 6:57 PM
In response to Adding A New Field
It appears the command is case sensitive. I had the same issue as Cameron. When I changed the to it...

Alvin 11/14/2014 12:49 PM
In response to Razor Web Pages E-Commerce - Adding A Shopping Cart To The Bakery Template Site
Great article Mike! When do you plan to extend the bakery shopping cart beyond this point?...

Gautam 11/14/2014 10:16 AM
In response to Web Pages - Efficient Paging Without The WebGrid
to get the count can we use only the below sql, why to join category and author table var sql =...