Click here to Skip to main content
15,311,716 members
Articles / Web Development / ASP.NET
Posted 5 Dec 2013


181 bookmarked

A free "Export to Excel" C# class, using OpenXML

Rate me:
Please Sign up or sign in to vote.
4.88/5 (102 votes)
17 Dec 2013CPOL4 min read
How to easily add an "export to Excel" feature to your app


It's amazing that even now, in 2013, there are so many developers still asking for help on how to write C# and VB.NET code to export their data to Excel.

Even worse, a lot of them will stumble on articles suggesting that they should write their data to a comma-separated file, but to give the file a .xls extension.

So today, I'm going to walkthrough how to use my C# "Export to Excel" class which you can add to your C# WinForms / WPF / ASP.NET application, using one line of code.

Depending on whether your data is stored in a DataSet, DataTable, or List<>, you simply need to call one of these three functions, and tell them what (Excel) file name you want to write to.

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

Here's a simple example.

We create a DataSet, fill it with some data (just add your own CreateSampleData function), then call the CreateExcelFile.CreateExcelDocument function, passing it the DataSet and a filename:

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

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

And that's all you have to do. The CreateExcelDocument function will create a "real" Excel file for you.

For example, if you had a created a DataSet containing three DataTables called:

  • Drivers
  • Vehicles,
  • Vehicle Owners,

..then here's what your Excel file would look like. The class would create one worksheet per DataTable, and each worksheet would contain the data from that DataTable.

Sample spreadsheet

The full source code for this C# class is freely downloadable here (click on the "Browse code" link in the left-hand panel), or you can download this full demo, plus a VB.NET version of the class, from my blog, MikesKnowledgeBase.

Adding the library to your application

The C# code above shows how easy it is to call the CreateExcelFile class.

DataSet ds = CreateSampleData();
CreateExcelFile.CreateExcelDocument(ds, "C:\\Sample.xlsx");

However, to use this library, you'll need to add two files from the free Microsoft OpenXML SDK:

  • DocumentFormat.OpenXml.dll: From the free Microsoft Open XML SDK library
  • WindowsBase.dll: From the Microsoft .NET Framework library

Add these two DLLs to your project's References section, and remember to set them to "Copy Local".

Copy Local

Then, just download the CreateExcelFile.cs file (via the "Browse code" link in CodeProject's left-hand panel), and add it to your application. 

And that's it.

Regardless of if your data is stored in a List<>, DataTable, or DataSet, you can export it to a "real" Office 2007 Excel .xlsx file using that one line of code.

And because it is created using the OpenXML library, you can run this code on machines which don't have Excel installed.


For ASP.NET developers, I've added three extra functions.

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)

Rather than creating the Excel file in a temporary directory, then having to load in the file and output it to the webpage's HttpResponse, you can get the library to write directly to the HttpResponse.

However, by default, this functionality is disabled (to prevent build issues for the non ASP.NET developers). To enable these three functions, you need to make two changes.

First, uncomment the top line of the CreateExcelFile.cs code, so that it now reads:


Now, you need to add a Reference to the System.Web .NET library:

Adding a reference

Once you've done these two steps, the CreateExcelFile library is ready to go.

For example, in this example, my ASP.NET C# code has a list of Employee records, stored in a List<Employeee>. I add an "Export to Excel" button to my webpage, and when the user clicks on it, I just need one simple call to the CreateExcelFile class.

// In this example, I have a defined a List of my Employee objects.<br />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);

And that's it. A real Excel file, in one line of code.

Going forward

You'll notice that this library is excellent for one job - writing plain, boring data to an Excel file. I haven't attempted to add any classes to add formatting, colors, pivot tables or anything else.

However, this class is an excellent way to get started (without paying for third-party software to create the Excel file for you), and if you want to take this further, you'll soon find that Googling will easily find you extra source code to add on top of this.

For example, if you wanted to add a background color to some of the cells in the Excel file, simply Google "open XML background color" and you'll have many articles showing you how to do this.

The reason I wrote this article is that I found that it was very hard to find a free, easy to use C# library which actually created the OpenXML Excel file in the first place.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Mike Gledhill
Software Developer
Switzerland Switzerland
Programming since the age of 15, with experience in C# and iPad software development.
Working as a software developer for a financial company in Zurich, Switzerland.

More developer tips'n'trip at my website:

Comments and Discussions

QuestionHtml tag not rendering Pin
Member 108100778-Aug-21 21:36
MemberMember 108100778-Aug-21 21:36 
QuestionChanging background color of rows Pin
computrans1-Jun-19 8:43
Membercomputrans1-Jun-19 8:43 
Questionworks fine in sample application with forms authentication.its not working in windows error but no file generated Pin
Member 1179141114-Sep-17 20:36
MemberMember 1179141114-Sep-17 20:36 
QuestionQuestion about functionality Pin
vinodajacob10-Aug-17 6:45
Membervinodajacob10-Aug-17 6:45 
QuestionExcel File does not generate from LinkButton Pin
vinodajacob18-Jul-17 6:35
Membervinodajacob18-Jul-17 6:35 
QuestionAdd Column Headers in bold Pin
Krishnanand Nayak. S18-Apr-17 1:18
MemberKrishnanand Nayak. S18-Apr-17 1:18 
SuggestionAdd => Cell Headers take enough space according to their content Pin
Member 1096978220-Mar-17 1:02
MemberMember 1096978220-Mar-17 1:02 
GeneralRe: Add => Cell Headers take enough space according to their content Pin
CHill6020-Mar-17 1:04
mveCHill6020-Mar-17 1:04 
QuestionHow to add a report header Pin
kwilder2-Mar-17 6:14
Memberkwilder2-Mar-17 6:14 
Questionroadmap Pin
kiquenet.com16-Feb-17 3:45
professionalkiquenet.com16-Feb-17 3:45 
QuestionDo you have a newer version to format the date so it's a short date? Pin
docdaven31-Jan-17 19:48
Memberdocdaven31-Jan-17 19:48 
AnswerRe: Do you have a newer version to format the date so it's a short date? Pin
PabloMarianoC11-Aug-17 4:13
professionalPabloMarianoC11-Aug-17 4:13 
QuestionNice work, saved my time too! Pin
Alejandro Gaio28-Nov-16 10:26
MemberAlejandro Gaio28-Nov-16 10:26 
QuestionYou save my time Pin
Daniel Sean24-Nov-16 5:10
MemberDaniel Sean24-Nov-16 5:10 
QuestionError Pin
Ugo Basile14-Nov-16 4:38
MemberUgo Basile14-Nov-16 4:38 
Generalworks just fine for Limited number of raw counts Pin
iDaGY23-Aug-16 5:52
MemberiDaGY23-Aug-16 5:52 
QuestionExcel file has been created but attempt to add records via Microsoft.ACE.OLEDB.12.0 is not working Pin
Member 1110404920-Apr-16 6:56
MemberMember 1110404920-Apr-16 6:56 
QuestionWorked really well Pin
Chris McClure10-Apr-16 17:20
MemberChris McClure10-Apr-16 17:20 
QuestionBest and one works super good Pin
ranjith.murthy20-Mar-16 1:44
Memberranjith.murthy20-Mar-16 1:44 
QuestionResponse does not exist in the current context Pin
oryginalnylogin27-Feb-16 3:30
Memberoryginalnylogin27-Feb-16 3:30 
QuestionGreat Job Mike Gledhill Pin
Member 1234612523-Feb-16 3:37
MemberMember 1234612523-Feb-16 3:37 
Questionworks fine locally, can't get it to work on a remote server Pin
Member 1227929021-Jan-16 9:40
MemberMember 1227929021-Jan-16 9:40 
AnswerRe: works fine locally, can't get it to work on a remote server Pin
Garth J Lancaster21-Jan-16 11:38
professionalGarth J Lancaster21-Jan-16 11:38 
GeneralRe: works fine locally, can't get it to work on a remote server Pin
Member 1227929022-Jan-16 1:17
MemberMember 1227929022-Jan-16 1:17 
PraiseExcellent Job Mike! Pin
rdzsjpr23-Dec-15 7:24
Memberrdzsjpr23-Dec-15 7:24 

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

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