Latest News (Sep 2014)
  • The C# class now writes the data to the Excel file using the OpenXmlWriter library.
  • My class has been downloaded 4,800 times in 10 months, from my CodeProject article.

Export data from a DataSet into a real Excel 2007 file

Ever wanted to add an "Export to Excel" function to your ASP.Net, WinForms or WPF application ?

This free C# and VB.Net library lets you export a DataTable or DataSet of data into a "real" Excel 2007 .xlsx file, using one line of code.

CreateExcelFile.CreateExcelDocument(myDataSet, myExcelPathFilename);

...or if you're using ASP.Net...

CreateExcelFile.CreateExcelDocument(myDataSet, myExcelFilename, Response);

You can download the full source code using the links below, so you can extend it to add Excel formatting, etc.

It uses the OpenXML libraries, rather than Microsoft's Visual Studio Tools for Office (VSTO) libraries, so you don't need to have Excel installed on your server.

The CreateExcelFile library

All of the code you'll need is contained in one class, CreateExcelFile, which I've saved in the file CreateExcelFile.cs (or CreateExcelFile.vb for the VB.Net version).

To use this class, you simply call its CreateExcelDocument function, passing it a DataSet variable (which contains the values you want writing into Excel cells), and the path+filename of the Excel file you wish to create.

Each DataTable within your DataSet will be saved into it's own Excel worksheet.

// Step 1: Create a DataSet, and put some sample data in it
DataSet ds = CreateSampleData();

// Step 2: Create the Excel .xlsx file
try
{
    string excelFilename = "C:\\Sample.xlsx";
    CreateExcelFile.CreateExcelDocument(ds, excelFilename);
}
catch (Exception ex)
{
    MessageBox.Show("Couldn't create Excel file.\r\nException: " + ex.Message);
    return;
}

Demo program

The attached Visual Studio 2010 C# and VB.Net WinForms demo shows how easy it is to use the CreateExcelFile library.

It consists of a simple dialog with one button on it (shown below).

When you click on the button, it'll create a DataSet and fill it with some sample data, and prompt you for a location to save our example Excel file to. It will then call the CreateExcelDocument function to create an Excel 2007 .xlsx file containing our DataSet's data, then open the file in Excel for you to admire.

Screenshot from the C# demo Screenshot from the C# demo

Notice how our demo application created a DataSet containing three DataTables in it, called Drivers, Vehicles & Vehicle Owners. The CreateExcelFile library then created an Excel Worksheet for each of these DataTable names, and wrote each DataTable's data into it.

Using the "Export to Excel" library in your own application

The CreateExcelFile library has two dependences:

  • DocumentFormat.OpenXml.dll
    From the Microsoft Open XML SDK library
  • WindowsBase.dll
    From the Microsoft .Net Framework library

I have included a copy of these two files in the source code's lib folder, but ideally, you should download the most recent version from the Microsoft website.

To use the library in your own code, simply add these two files, and the CreateExcelFile.cs file to your Visual Studio project, then add the two .dll files to the References section of your project.

Also, you need to make sure that these two files have the "Copy Local" field set to true. Without this, when you deploy your app, it won't copy the .dlls to your bin directory, and IIS will complain that it can't find the OpenXML libraries.

Then just call the static CreateExcelDocument function, as shown above.

CreateExcelFile.CreateExcelDocument(ds, excelFilename);

I have deliberately left this library's source code available for you to view and alter, as desired.

Exporting from a List<> or DataTable

With a little help from a discussion on CodeGuru, I added two extra functions, so you can now call the CreateExcelDocument function in three ways:

public static bool CreateExcelDocument<T>(List<T> list, string xlsxFilePath)
public static bool CreateExcelDocument(DataTable dt, string xlsxFilePath)
public static bool CreateExcelDocument(DataSet ds, string xlsxFilePath)

..so you should find it really easy to export your data to Excel from any of these formats.

Using the library in an ASP.Net application

November 2013: With help from my fellow developers, I have made the C# library even easier to use in an ASP.Net application. The ExportToExcel class now lets you create an Excel file without writing to a temporary file first. You just need to pass the "Response" as a parameter.

// In this example, I have a defined a List of my Employee objects.
class Employee;
List<Employee> listOfEmployees = new List<Employee>();

...

// The following ASP.Net code gets run when I click on my "Export to Excel" button.
protected void btnExportToExcel_Click(object sender, EventArgs e)
{
    // It doesn't get much easier than this...
    CreateExcelFile.CreateExcelDocument(listOfEmployees, "Employees.xlsx", Response);
}

By default, this functionality is disabled in the C# file, so that non-ASP.Net developers don't get build errors when attempting to use the library. To enable the functionality, you need to manually make two small changes:

First, uncomment the first line of code in the CreateExcelFile.cs file, so it looks like this:

#define INCLUDE_WEB_FUNCTIONS

Then add a new Reference, and select the System.Web library.

Add Reference..

And that's it. You can now use the three new web-friendly functions for exporting to Excel.

public static bool CreateExcelDocument<T>(List<T> list, string filename, System.Web.HttpResponse Response)
public static bool CreateExcelDocument(DataTable dt, string filename, System.Web.HttpResponse Response)
public static bool CreateExcelDocument(DataSet ds, string filename, System.Web.HttpResponse Response)

Cool, hey ?

You're welcome to use and adapt this code as you like, but - please - if you like it, leave me a comment below.

Setting the Excel column widths

By default, the CreateExcelFile class just creates a valid Excel 2007 with no formatting, colors, borders, etc.

If you wanted to change this code to set the widths of the columns in your Excel file, below are the changes you'd need to make.

First, you need to add a few lines to the CreateParts function (shown in red):

private static void CreateParts(DataSet ds, SpreadsheetDocument spreadsheet)
{
  // Loop through each of the DataTables in our DataSet, and create a new Excel Worksheet for each.
  uint worksheetNumber = 1;
  foreach (DataTable dt in ds.Tables)
  {
    // For each worksheet you want to create
    string workSheetID = "rId" + worksheetNumber.ToString();
    string worksheetName = dt.TableName;

    WorksheetPart newWorksheetPart = spreadsheet.WorkbookPart.AddNewPart<WorksheetPart>();
    newWorksheetPart.Worksheet = new DocumentFormat.OpenXml.Spreadsheet.Worksheet();

    // If you want to define the Column Widths for a Worksheet, you need to do this *before* appending the SheetData
    // http://social.msdn.microsoft.com/Forums/en-US/oxmlsdk/thread/1d93eca8-2949-4d12-8dd9-15cc24128b10/
    //
    // The following example sets the column width, for all columns where we have data, to 20 pixels.


    int columnWidthSize = 20;
    Columns columns = new Columns();

    for (int colInx = 0; colInx < dt.Columns.Count; colInx++)
    {
      Column column = CustomColumnWidth(colInx, columnWidthSize);
      columns.Append(column);
    }
    newWorksheetPart.Worksheet.Append(columns);


    // create sheet data

    newWorksheetPart.Worksheet.AppendChild(new DocumentFormat.OpenXml.Spreadsheet.SheetData());

    // save worksheet

    WriteDataTableToExcelWorksheet(dt, newWorksheetPart);
    newWorksheetPart.Worksheet.Save();

Then, add the following function just below the WriteDataTableToExcelWorksheet function:

private static Column CustomColumnWidth(int columnIndex, double columnWidth)
{
    // This creates a Column variable for a zero-based column-index (eg 0 = Excel Column A), with a particular column width.
    Column column = new Column();
    column.Min = (UInt32)columnIndex + 1;
    column.Max = (UInt32)columnIndex + 1;
    column.Width = columnWidth;
    column.CustomWidth = true;
    return column;
}

If you wanted to calculate the column widths, based on the data in each column, it's not easy.
Have a read of this article:
http://polymathprogrammer.com/2010/01/11/custom-column-widths-in-excel-open-xml/

Downloads

C# VB.Net Filename Description
ExportToExcel.zip The full Excel demo, showing how to use the CreateExcelFile library code, and the Open XML libary files.


CreateExcelFile.cs / .vb Just the C#/VB.Net source code file for the CreateExcelFile class.

ExpotToExcelExe.zip The executable (.exe) file of the Demo, if you just want to see what the application looks like.
Note: This zip file contains a copy of the .exe file created by the Visual Studio project which you can download using the link above. This .zip file is safe, but your anti-virus software might complain about it or block it, as it contains an executable file.

Last updated: March 2014

Liked it ? Like it !

If you found this article useful, please support the costs of running this website by clicking on the Donate button at the top of this webpage.


License

Copyright (C) 2014 MikesKnowledgeBase

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Release history

March 2014

  • Now writes the Excel data using the OpenXmlWriter classes.
    This is a much more memory efficient method, and will prevent issues when writing large Excel files.

November 2013

  • Added new ASP.Net functions to (just) the C# code, to let you write Excel directly to the page's HttpResponse, rather than writing to a temporary file first.

February 2013

  • Added a VB.Net version of the ExportToExcel classes.

January 2013 - Excel 2010 update

  • Updated the C# and VB.Net classes to cope with nullable column types.
  • Also, it no longer writes a "0" to the Excel file when a numeric column has a null value in it.
  • There was also an issue with OLEDB being unable to open the .xlsx files.

August 2012

  • Fixed a couple of problems with exporting numeric values to an Excel 2007 file. Strangely, the OpenXML libraries would create "corrupted" files when directly writing lots of numeric values to the file. My solution has been to convert all values in the numeric columns into a double, and then to write the value to the Excel file.
  • There is also an issue when writing lots of rows (30,000+) to the Excel file. The OpenXML libraries simply seem to hang when there's too much data to write. I haven't implemented a solution to this problem yet.

References

Importing data from Excel into SQL Server
http://mikesknowledgebase.com/pages/SQLServer/ImportExcelIntoSQLServer.htm

"Introduction to Open XML SDK 2.0"
http://msdn.microsoft.com/en-us/library/bb448854.aspx

"How to create an Excel 2007 file, from scratch:"
http://blogs.msdn.com/b/chrisquon/archive/2009/07/22/creating-an-excel-spreadsheet-from-scratch-using-openxml.aspx

"Writing data into excel document using openxml"
http://www.prowareness.com/blog/?p=476

"Convert a List<T> into a DataTable"
http://www.codeguru.com/forum/showthread.php?t=450171

Comments

blog comments powered by Disqus