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


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


It' s not a nice solution but it works.

The first row of your excel-template file contains the fields.
On the second row, add zeros to the columns that you want to be integers, or for example add $ 0,00 to the columns you want to be values.

This makes sure that when you export your data, all columns will be formatted perfectly according to how you formatted the fields in the second row....
Of course, the second row of the excel sheet has crap information, but in my case it's really worth it...

Recent Comments

adam 05/10/2015 14:35
In response to Integrating Web API with ASP.NET Razor Web Pages
Can you re-open this web api project in webmatrix, once you've added web api? Basically I'm looking...

nish 24/09/2015 18:48
In response to Managing Checkboxes And Radios In ASP.NET Razor Web Pages
Very Interresting stuff! it really helped me to send an int value by checking a checkbox!...

Uğur Dinç 24/09/2015 16:45
In response to Scheduled Tasks In ASP.NET With Quartz.Net
Simplest and best explanation on Quartz.NET. Thank you!...

woo 24/09/2015 15:34
In response to Implementing Google's EU End User Consent Policy
Is there any way for the banner to appear only to EU visitors? I am referring to the jQuery code...

Justin 24/09/2015 11:10
In response to Using ASP.NET Identity with Razor Web Pages
Hi Mike, Very helpful article again, thanks. One query that I'm trying to work out is how you to...

hb 23/09/2015 23:12
In response to WebMatrix Opens Wrong Version Of Visual Studio
Mike - I got this working when I went decided to look at the community edition of VS2015 and tried I...

Muneer 22/09/2015 14:55
In response to Scheduled Tasks In ASP.NET With Quartz.Net
I have an error with these two is not recognizing the commands. am i missing any library? I am web...

David 22/09/2015 13:57
In response to iTextSharp - Working with Fonts
Mike your articles about itextsharp are excellent, really helpful and well written. In the future...

Peter 22/09/2015 06:39
In response to Accessing Your Model's Data from a Controller
Thanks.Got it. ...

sreedhar kandukuri 21/09/2015 14:05
In response to Integrating Web API with ASP.NET Razor Web Pages
Nice Overview...