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.