Click here to Skip to main content
Licence MIT
First Posted 15 Apr 2007
Views 193,141
Downloads 4,231
Bookmarked 88 times

DataTable to Excel

By | 15 Apr 2007 | Article
A quick and easy way to format and export a DataTable to an Excel spreadsheet

Introduction

A common task I've run across is the need to export a DataTable to an Excel spreadsheet. It's a great way to distribute reports, etc. to users. It also seems like an obvious translation, considering the way that DataSets are usually presented in DataGrid controls.

Unfortunately, the methods I have found so far for doing this have been rather ugly - they involve iterating through the DataTable items and manually writing to the output file, line-by-line, in the correct format. Then, in a stroke of luck, I was assigned a simple ASP.NET project at work (I normally work in Windows Forms), and while working on that, I found a very simple way of accomplishing this task, with the added bonus of being able to easily format the output spreadsheet.

Using the code

The basic trick is that Excel can open HTML tables, so the idea is to create a DataGrid web control (which you can use whether or not your project is in ASP.NET), use databinding to fill the control with information from your DataSet, set any formatting (bolded text, background colors, etc), then have the DataGrid render itself to an output file with Excel's ".XLS" extension.

Please note that you need to add a reference to "System.Web" in your project in order to use the System.Web.UI.WebControls namespace!

Here is an example. I am using a DataSet named "data" containing a Table named "Stats":

// create the DataGrid and perform the databinding
System.Web.UI.WebControls.DataGrid grid = 
            new System.Web.UI.WebControls.DataGrid();
grid.HeaderStyle.Font.Bold = true;
grid.DataSource = data;
grid.DataMember = data.Stats.TableName;

grid.DataBind();

// render the DataGrid control to a file
using(StreamWriter sw = new StreamWriter("c:\\test.xls"))
{
    using(HtmlTextWriter hw = new HtmlTextWriter(sw))
    {
        grid.RenderControl(hw);
    }
}

If you then open the output file in a text editor, you will see that it just contains simple HTML.

Points of Interest

As someone who works mostly with Windows Forms, some of the above code seems non-obvious. Here are some important differences I found between the regular Windows Forms controls and the Web controls:

  • Databinding with Web controls must be performed manually! You set the DataSource and DataMember properties as usual, but the databinding will not occur until you make the "DataBind()" call yourself.
  • Rendering the control requires two output streams: one is the HtmlTextWriter, which is what the Web grid can render itself to, and the second is the StreamWriter, which the HtmlTextWriter writes itself to. Compare this to a normal ASP.NET webpage, where instead of using a StreamWriter to write to a file, the HtmlTextWriter would probably write to a web page in memory.

Finally, a word of warning - once the user has opened the file in Excel and saved changes to it, the file will no longer contain a simple HTML table as Excel will rewrite it with its own file format.

License

This article, along with any associated source code and files, is licensed under The MIT License

About the Author

ekrlanw

Software Developer

United States United States

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralSimple and effective PinmemberQCJim2:31 6 Jan '12  
QuestionProblem while exporting special characters like ü Pinmembervishal pareek2:41 1 Sep '11  
QuestionA proper way PinmemberCikaPero22:29 20 Jul '11  
GeneralBest Way Pinmemberabhijitwalke16:53 25 May '11  
GeneralMy vote of 4 PinmemberAmar Karandikar23:39 5 Sep '10  
GeneralIt works. Thanks! Pinmemberlarno5:10 8 May '10  
GeneralGreat Help.. Thanks Pinmemberhardikprogram4:17 20 May '09  
QuestionHow to add formating to Excel after Exporting PinmemberSachin Pisal7:05 19 Jan '09  
GeneralGreat and simple Solution. Thanks! PinmemberMember 143196613:32 8 Aug '08  
General5 from me, too PinmemberScott Bruno9:12 27 Jun '08  
GeneralAlternative way PinmemberBarbaMariolino2:33 17 Jun '08  
General5 from me! PinmemberDuong Tran20:47 14 Jun '08  
Generaldownloading this file PinmemberFrank Silva2:35 3 Jan '08  
GeneralRe: downloading this file PinmemberJacob Klint8:25 3 Jan '08  
GeneralHello Pinmemberfarhit1:18 26 Oct '07  
Generalmay need flush and close, too PinmemberCathieA10:45 31 Jul '07  
GeneralRe: may need flush and close, too PinmemberJacob Klint13:08 14 Aug '07  
QuestionSupported by Excel 2000? Pinmemberlizrd82510:36 12 Jun '07  
AnswerRe: Supported by Excel 2000? PinmemberJacob Klint13:18 12 Jun '07  
GeneralRe: Supported by Excel 2000? Pinmemberlizrd82510:10 13 Jun '07  
GeneralThanks - saved me loads of time! Pinmembernzmike12:32 8 May '07  
Questioncovert to VB Pinmemberbobcarrretta6:32 17 Apr '07  
AnswerRe: covert to VB PinmemberBen[dog]11:55 17 Apr '07  
GeneralThis is not how you export data! Pinmemberyang yu 17999996:48 16 Apr '07  
This is not how you export any kind of data to any other data format. There are various data transformation methods including xml transformer or DTS packages, SSIS, or simply Data reconstruction. But, you do not ever export to html then hope an external application will understand html then save it using its own transform method.
 
Horrible horrible article.
GeneralRe: This is not how you export data! [modified] PinmemberJacob Klint8:23 16 Apr '07  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web01 | 2.5.120529.1 | Last Updated 15 Apr 2007
Article Copyright 2007 by ekrlanw
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid