Saturday, October 07, 2006

Exporting Data to Excel

Original Address: http://www.developer.com/net/asp/article.php/3633891

A common request of users is to be able to download data for use in Microsoft Excel. This is actually fairly easy to accomplish without a lot of extra work.

I do most of my database work with DataTable objects, as I don't need the overhead of a DataSet. I also have a Database wrapper class that is able to easily retrieve data from a SQL Server database. Once I use my function to get my DataTable, I can start exporting the data. For this example, however, I'll use the traditional SqlDataAdapter method to retrieve the data initially.

There are a few tricks to making this work.
First, you have to create an ASPX page with no HTML content in it. The only thing that should be in the ASPX page is the Page directive at the top.
The second trick is to clear the existing content and send down a new content type. For Excel, you use a content type of application/vnd.ms-excel. This tells your Web browser to expect something that can be handled within Excel.
The third trick is to send down the data tab-delimited per column and a newline at the end of each row.
After that, Excel does the rest of the work for you.