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
Member
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   
QuestionException :(membersuvsuv27 Nov '12 - 19:28 
I am getting "System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown." Frown | :(
 
-Suv
GeneralSimple and effectivememberQCJim6 Jan '12 - 2:31 
Ok so it doesn't have all the whistles and bells of some solutions but for getting basic data into an Excel sheet this works great. After playing around with various more complex solutions this does everything I want.
Sometimes it's easy to overlook the obvious! Smile | :)
QuestionProblem while exporting special characters like ümembervishal pareek1 Sep '11 - 2:41 
When some special characters like 'ü' are exported from grid, then that character is displayed as some other special character 'ü'
QuestionA proper waymemberCikaPero20 Jul '11 - 22:29 
This doesn't export to Excel format (XLS, XLSX), it just exports to HTML that Microsoft Excel interprets right, although you assigned .xls file extension.
 
To me this is just wrong. It would be much better to export it as a CSV file, if you don't need any formatting.
 
If you need to export DataTable to real Excel format (XLS, XLSX), I recommend this Excel C# / VB.NET library.
 
It doesn't use Excel automation and is very fast.
 
Here is an Excel C# sample how to export DataTable to Excel:
var ef = new ExcelFile();
ef.Worksheets.Add(dataTable.TableName).InsertDataTable(dataTable, 0, 0, true);
ef.SaveXls(dataTable.TableName + ".xls");

GeneralBest Waymemberabhijitwalke25 May '11 - 16:53 
public void dtToCsv(DataTable dt)
{
 
StreamWriter sw = new StreamWriter(@"C:\Temp\" + @"sample" + ".csv", true); //Open new file
try
{
int colCount = dt.Columns.Count; //Total number of Columns
 
for (int c = 0; c < colCount; c++) //Write different column names with ','
{
sw.Write(dt.Columns[c]);
if (c < colCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
 
foreach (DataRow dr in dt.Rows)
{
for (int r = 0; r < colCount; r++)
{
if (!Convert.IsDBNull(dr[r]))
{
if (dr[r].GetType().ToString() == "System.String") //Will check column is string or not
{
sw.Write(dr[r].ToString());
}
else
{
sw.Write(dr[r].ToString());
}
}
if (r < colCount - 1)
{
sw.Write(",");
}
 
}
sw.WriteLine();
}
sw.WriteLine(sw.NewLine);
sw.Write("File Compiled at " + System.DateTime.Now);
}
finally
{
sw.Close();
}
 
}
GeneralMy vote of 4memberAmar Karandikar5 Sep '10 - 23:39 
This is really quick way of generating the excel format. Other approaches take lot of time. This approach helped in getting the excel export in just 10mins. Thats great saving. Thanks for sharing this.
GeneralIt works. Thanks!memberlarno8 May '10 - 5:10 
A really great simple solution.
GeneralGreat Help.. Thanksmemberhardikprogram20 May '09 - 4:17 
a
QuestionHow to add formating to Excel after ExportingmemberSachin Pisal19 Jan '09 - 7:05 
This method of exporting is really awesome
meanwhile I have one question how to keep apply formating for excel , I means the date time is exporting as time part 00:00 or if any column as currency then how to apply currency formate
 
Regards
Sac
GeneralGreat and simple Solution. Thanks!memberMember 14319668 Aug '08 - 13:32 
I'ved worked with several methods to export tables to excel and all of them suck! Plus most of them have bad memory management and are more slow. This is just Great for a simple task. Thanks a lot!
 
Ariel

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

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