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">
            tableStyle : "table",
            alternatingRowStyle : "alternate",
            headerStyle : "header",
            columns: grid.Columns(
                grid.Column("CustomerID", "ID"),
                grid.Column("CompanyName", "Company Name"),
                grid.Column("ContactName", "Contact Name"),
        <img src="/images/excel-icon.png" id="excel" alt="Export to Excel" title="Export to Excel" />

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();

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){

    Response.AddHeader("Content-disposition", "attachment; filename=report.xls");
    Response.ContentType = "application/octet-stream";

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:
Last Updated:
Posted by:
Total Views to date: 10508


- ARul


- 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?

- 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?

- Mike


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

- Gautam

hello mike,

I am logging exceptions in _pageStart.cshtml file

this line

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()

- Mike


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.

- 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.

- Mike


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 I end up deleting quite a lot. The kind of things that will ensure your comment is deleted without ever seeing the light of day are as follows:

  • Requests to fix your code (post a question to forums.asp.net instead, please)
  • Gratuitous links to your own site or product
  • Anything abusive or libellous
  • Spam

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

Lorenzo 3/26/2015 8:21 AM
In response to iTextSharp - Introducing Tables
Hi Mike How can I add padding to all cells in the table? Kind Regards Lorenzo...

Satyabrata Mohapatra 3/25/2015 8:11 AM
In response to How To Send Email In ASP.NET MVC
Great article. Simple and up to the point....

Afzaal Ahmad Zeeshan 3/24/2015 8:17 PM
In response to How To Send Email In ASP.NET MVC
A great way to teach the MVC framework for sending the emails... Also, what I found helpful was the...

Jim H 3/24/2015 2:32 PM
In response to Migrating From Razor Web Pages To ASP.NET MVC 5 - Model Binding And Forms
Thank you. This helps....

wazz 3/22/2015 5:48 AM
In response to Posting Data With jQuery AJAX In ASP.NET Razor Web Pages
great info!!...

rael 3/21/2015 8:53 PM
In response to Getting the identity of the most recently added record
I spent hours trying to figure how to achieve this in C#. This article helped me. Thanks a lot...

Stephen 3/21/2015 8:48 PM
In response to Ajax with Classic ASP using jQuery
This was very helpful, thanks:)...

patrick voes 3/19/2015 10:19 AM
In response to iTextSharp - Introducing Tables
Thank you! very helpfull....

Bigmachini 3/19/2015 6:13 AM
In response to ASP.NET MVC DropDownLists - Multiple Selection and Enum Support
This just made my day, afternoon, evening, night... was looking for a way of doing this without to a...

Bobbyg 3/19/2015 4:14 AM
In response to HTML Helpers For Forms In Razor Web Pages
Nice article. There are bugs in MVC 5 with dropdowns retaining values from other screens and them. I...