Click here to Skip to main content
Click here to Skip to main content

DataTable to Excel

By , 15 Apr 2007
 

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

Jacob Klint
Software Developer
United States United States
No Biography provided

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.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralRe: This is not how you export data! [modified]memberJacob Klint16-Apr-07 8:23 
"horrible" - that's a little harsh, n'est-ce pas? Smile | :)
 
Excel has official support for HTML data - just go to File->Open, and you'll see "*.html" files in its list of openable formats. All I've done here is to change the file extension to force Excel to open the file rather than a web browser.
 
Certainly this method doesn't work for all situations, but for straightforward, one-way transfer of raw data from code to Excel (along with style options), I've yet to find a simpler method. If you have, however, then please write it up in an article for all our benefit.
GeneralRe: This is not how you export data!membermichael1watson18-Apr-07 1:04 
What about just creating a .csv file?
It's only basic text though without formatting or graphics, but opens in Excel just fine.
I'd imagine you'd just be looping through the rows and cells (nested loop!) of the DataTable and writing out to a text file (via a StringBuilder), simply comma-separating the cell values and watching out for quotes in the cell content... ?
 
Oherwise, thank you for your very nice article presenting a handy, quick way to export data via a datagrid! Saving it to my snippets right now...
GeneralRe: This is not how you export data!memberBen[dog]17-Apr-07 3:40 
Sorry sir, but this is a really nice technique, on complement of being a cuning use of existing controls and their rendering capabilities using very little coding, it does the job just fine for a basic export.
I've had to work on quick fixes like this to give some clients a simple export to excel function, all that in a cost effective development manner and this is just right.
 
Yes one could spend 30 hours doing it proper with DTS packages, XML Decepticons transformers, whatever one's into, but for a sweet sweet 20 minutes on-the-fly solution, there you have it.
 
Spot on Jacob.
 
Great Great article. Cool | :cool:
GeneralRe: This is not how you export data!memberJacob Klint17-Apr-07 8:56 
Thanks Ben, glad to see someone else understands the usefulness of this.
 
Hmm..."XML Decepticons transformers"...that's in the "System.Xml.StuffThatWasCoolInTheEighties" namespace, right? Big Grin | :-D
GeneralRe: This is not how you export data!memberTiamatPt18-Apr-07 4:12 
Like already mentioned, when you are simply trying to export a structure or data, this method is very very good. I don't know about other people, but my time is short and if I can have just what I need with so little work, then all I can say is thank you.
GeneralRe: This is not how you export data!memberCikaPero26-Apr-11 23:03 
Hi,
 
if you need to export DataSet to Excel format (*.xls) or XML based Excel format (XLSX or ODS), you can do it easily with this Excel C# / VB.NET component.
 
Here is an Excel C# sample:
var ef = new ExcelFile();
 
foreach (DataTable dataTable in dataSet.Tables)
    ef.Worksheets.Add(dataTable.TableName).InsertDataTable(dataTable, 0, 0, true);
 
ef.SaveXlsx(dataSet.DataSetName + ".xlsx");

Questionusing an existing xls filememberSeishin#15-Apr-07 21:52 
Hi!
this is really useful, but what if I'm using an already made xls file as a template with few sheets and formulas? right now i just copy the template file and fill proper cells row-by-row..
 
life is study!!!

AnswerRe: using an existing xls filememberJacob Klint17-Apr-07 13:48 
I'm guessing you're opening the template file in code as just a text stream, then doing a search and replace to fill in the proper cells? Or are you doing something else?
 
Off the top of my head, I don't think the method in this article would help you much. It's really meant for situations where you already do all the processing within a dataset and just want to send that data off to the outside world, not where you want to modify an existing spreadsheet.
GeneralRe: using an existing xls filememberSeishin#17-Apr-07 19:12 
Hi!
Actually I'm using Interops - Excel._Application etc objects..
I'm opening the file and then copy data row-by-row from dataset, something like this:
 
DataRow rowToCopy = ds.Rows[i];
Range range = xlSomeWorksheet.get_range("A" + i.ToSthing(), "D" + i.ToSthing());
 
range.Value2 = rowToCopy;
 
in a for loop..
 
life is study!!!

AnswerRe: using an existing xls filemembergg423712-Nov-09 1:13 
You can't use HTML export technique for that scenario. You could do it if your template could be transformed into HTML, but with multiple sheets and formulas I think it is impossible.
 
You should take a look at GemBox.Spreadsheet .NET Excel component for reading and writing XLS, XLSX, CSV and HTML files.
 
Here is an example how to export DataTable to Excel file using GemBox.Spreadsheet library.

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

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