Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

What is the best tool for creating an Excel Spreadsheet with C#?

Ideally, I would like open source so I don't have to add any third party dependencies to my code, and I would like to avoid using Excel directly to create the file (using OLE Automation.)

The .CSV file solution is easy, and is the current way I am handling this, but I would like to control the output formats.


EDIT: I am still looking at these to see the best alternative for my solution. Interop will work, but it requires Excel to be on the machine you are using. Also the OLEDB method is intriguing, but may not yield much more than what I can achieve with CSV files. I will look more into the 2003 xml format, but that also puts a > Excel 2003 requirement on the file.

I am currently looking at a port of the PEAR (PHP library) Excel Writer that will allow some pretty good XLS data and formatting and it is in the Excel_97 compatible format that all modern versions of Excel support. The PEAR Excel Writer is here: PEAR - Excel Writer

share|improve this question
75  
I amusing in a sad way to see moderators close topics that are so overwhelmingly popular with the community that uses it. Clearly the goals of the moderators are out of sync and this can't be a good thing for the site or the community. – ChadD Oct 9 '12 at 20:01
31  
339 upvotes, 236 bookmarks, and an accepted answer with 180 upvotes. Clearly this should be closed as it's completely useless garbage. Well done wise moderator. – Samuel Meacham Oct 31 '12 at 17:28
1  
yeah, the decision to close this was overbearing. all questions are open to debate, and extended discussions are often very useful to understanding a problem. choosing a way to export to excel is no different than choosing an mvc rendering engine or a string parsing algorithm... there are pros and cons which can be hashed out in this format, with the most popular answer bubbling to the top. please reopen this 'AS IS' – 35434333 Dec 12 '12 at 20:49
8  
With 43 answers (twelve of which were useless enough to warrant deletion), can there be any doubt that this question solicited debate, arguments, polling or extended discussion? With 31 remaining answers (including an accepted one), why would the question need to be reopened? – Robert Harvey Dec 19 '12 at 0:51
3  
@RobertHarvey It makes sense to close it, but for being "not constructive"? Is that the only option you guys have when you close stuff? – Mikey G Jan 30 at 19:39
show 1 more comment

closed as not constructive by Kev Jan 27 '12 at 2:04

As it currently stands, this question is not a good fit for our Q&A; format. We expect answers to be supported by facts, references, or specific expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, see the FAQ for guidance.

31 Answers

1 2
up vote 240 down vote accepted

You can use a library called ExcelLibrary. It's a free, open source library posted on Google Code:

ExcelLibrary

This looks to be a port of the PHP ExcelWriter that you mentioned above. It will not write to the new .xlsx format yet, but they are working on adding that functionality in.

It's very simple, small and easy to use. Plus it has a DataSetHelper that lets you use DataSets and DataTables to easily work with Excel data.

ExcelLibrary seems to still only work for the older Excel format (.xls files), but may be adding support in the future for newer 2007/2010 formats.

You can also use EPPlus, which works only for Excel 2007/2010 format files (.xlsx files).

There are a few known bugs with each library as noted in the comments. In all, EPPlus seems to be the best choice as time goes on. It seems to be more actively updated and documented as well.

Also, as noted by @АртёмЦарионов below, EPPlus has support for Pivot Tables and ExcelLibrary may have some support (Pivot table issue in ExcelLibrary)

Here are a couple links for quick reference:
ExcelLibrary - GNU Lesser GPL
EPPlus - GNU Library General Public License (LGPL)

Here some example code for ExcelLibrary:

Here is an example taking data from a database and creating a workbook from it. Note that the ExcelLibrary code is the single line at the bottom:

//Create the data set and table
DataSet ds = new DataSet("New_DataSet");
DataTable dt = new DataTable("New_DataTable");

//Set the locale for each
ds.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
dt.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;

//Open a DB connection (in this example with OleDB)
OleDbConnection con = new OleDbConnection(dbConnectionString);
con.Open();

//Create a query and fill the data table with the data from the DB
string sql = "SELECT Whatever FROM MyDBTable;";
OleDbCommand cmd = new OleDbCommand(sql, con);
OleDbDataAdapter adptr = new OleDbDataAdapter();

adptr.SelectCommand = cmd;
adptr.Fill(dt);
con.Close();

//Add the table to the data set
ds.Tables.Add(dt);

//Here's the easy part. Create the Excel worksheet from the data set
ExcelLibrary.DataSetHelper.CreateWorkbook("MyExcelFile.xls", ds);

Creating the Excel file is as easy as that. You can also manually create Excel files, but the above functionality is what really impressed me.

share|improve this answer
92  
ExcelLibrary has been superseded by the exceptional EPPlus - epplus.codeplex.com. Jan updates it regularly. Have been using it and it is one of the finest open source projects we've worked with. – Mark A Nov 4 '10 at 0:11
2  
No. Use EppPlus - epplus.codeplex.com. It's the latest greatest. Supports formatting. I use it. – Bill Paetzke Nov 5 '10 at 1:34
23  
It seems that ExcelLibrary only supports .xls and EPPlus only .xlsx so they complement each other. – J-mster Feb 4 '11 at 15:07
4  
I've written a library to let you export any DataSet, DataTable or List<> directly into an Excel 2007 file, using one line of code. Full (and free) details and source code available here: mikesknowledgebase.com/pages/CSharp/ExportToExcel.htm – Mike Gledhill Nov 23 '11 at 12:02
4  
EPPlus is now LGPL, so that last concern should no longer apply – Tao Feb 8 '12 at 13:25
show 13 more comments

If you are happy with the xlsx format, try my codeplex project... EPPlus. Started it with the source from ExcelPackage, but today it's a total rewrite. Supports ranges, cell styling, charts, shapes, pictures, namesranges, autofilter and a lot of other stuff

share|improve this answer
3  
Epplus is great. – Carles Company Jun 21 '10 at 21:30
1  
Excellent library! +1 Especially for adding Stream support in the constructor! – hmemcpy Aug 28 '10 at 14:57
1  
Yes, I guess i should. My "marketing" so far is a few posts here. I'll try to do something after I have released the new version in a few weeks (which will include encryption and table support and a few other things). Feel free to help me out if you want to :) – Jan Källman Nov 9 '10 at 7:52
19  
One drawback of EPPlus is its licensing (currently GPL). Because of this, we cannot use this project. – dana Jun 30 '11 at 21:29
20  
License is now LGPL, release notes here: epplus.codeplex.com/releases/view/79802 – Simon D Feb 5 '12 at 12:30
show 5 more comments

I've used with success the following open source projects:

  • ExcelPackage for OOXML formats (Office 2007)

  • NPOI for .XLS format (Office 2003). NPOI 2.0 (Alpha) also supports XLSX.

Take a look at my blog posts:

Creating Excel spreadsheets .XLS and .XLSX in C#

NPOI with Excel Table and dynamic Chart

share|improve this answer
1  
Great blog posts, they helped a lot! – Jim Counts Apr 12 '10 at 21:52
3  
A note on NPOI - Row and Column references are zero-based. Does work well for populating an existing template. – John M Apr 30 '10 at 13:45

You can use OLEDB to create and manipulate Excel files. Check this: Reading and Writing Excel using OLEDB.

Typical example:

using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\temp\\test.xls;Extended Properties='Excel 8.0;HDR=Yes'"))
{
  conn.Open();
  OleDbCommand cmd = new OleDbCommand("CREATE TABLE [Sheet1] ([Column1] string, [Column2] string)", conn);
  cmd.ExecuteNonQuery();
}

EDIT - Some more links:

share|improve this answer
1  
I've just tested this connection and it failed on a Windows Server 2008 R2 x64 RC, seems like one have to install the 2007 Office System Driver: Data Connectivity Components [microsoft.com/downloads/… – Chris Richner Jun 16 '09 at 7:31
12  
Be very careful with this -- it's a big ugly cludge (for example, sometimes it guesses a column type and discards all the data that does not fit). – dbkk Sep 29 '09 at 9:02
4  
One should be very careful if using this method. I've found it very flaky for data that isn't in a perfect format. – Nazadus Jun 9 '10 at 16:03
1  
Correct - Jet does not work on 64 bit systems. – Holy Christ Jun 8 '11 at 13:59
show 1 more comment

The commercial solution, SpreadsheetGear for .NET will do it.

You can see live ASP.NET (C# and VB) samples here and download an evaluation version here.

Disclaimer: I own SpreadsheetGear LLC

share|improve this answer
2  
It was likely voted down because it reads like an advertisement. – Gavin Miller Feb 12 '09 at 15:09
1  
You have a great product but I think a lot of people here are expecting free solutions. That might explain the down votes. – md1337 Feb 3 '11 at 18:43
3  
I think you should have kept in the source code; there's nothing quite like seeing exactly what a tool is like to work with like the source... – sarnold May 24 '11 at 3:05
show 3 more comments

A few options I have used:

If XLSX is a must: ExcelPackage is a good start but died off when the developer quit working on it. ExML picked up from there and added a few features. ExML isn't a bad option, I'm still using it in a couple of production websites.

For all of my new projects, though, I'm using NPOI, the .NET port of Apache POI. NPOI 2.0 (Alpha) also supports XLSX.

share|improve this answer
show 3 more comments

And what about using Open XML SDK 2.0 for Microsoft Office?

A few benefits:

  • Doesn't require Office installed
  • Made by Microsoft = decent MSDN documentation
  • Just one .Net dll to use in project
  • SDK comes with many tools like diff, validator, etc

Links:

share|improve this answer
1  
Important to note that the DLL for this is just over 5 MB and limited to Office 2007 formats. But certainly the easiest and fastest solution which works for me. – Josh Brown Sep 20 '11 at 13:03
2  
Just a heads up that v2.5 is out and can be downloaded here. – Snuffleupagus Jan 4 at 16:47
show 1 more comment

An extremely lightweight option may be to use HTML tables. Just create head, body, and table tags in a file, and save it as a file with an .xls extension. There are Microsoft specific attributes that you can use to style the output, including formulas.

I realize that you may not be coding this in a web application, but here is an example of the composition of an Excel file via an HTML table. This technique could be used if you were coding a console app, desktop app, or service.

share|improve this answer
show 1 more comment

You actually might want to check out the interop classes. You say no OLE (which this isn't), but the interop classes are very easy to use.

You might be impressed if you haven't tried them.

Please be warned of Microsoft's stance on this:

Microsoft does not currently recommend, and does not support, Automation of Microsoft Office applications from any unattended, non-interactive client application or component (including ASP, ASP.NET, DCOM, and NT Services), because Office may exhibit unstable behavior and/or deadlock when Office is run in this environment.

share|improve this answer
3  
But you have to make sure that you dispose of everything manually, otherwise you will leak memory – MagicKat Sep 29 '08 at 22:40
6  
@Ricky B: Also, in my experience with the interop is that it does use excel. Every time we used it, if Excel wasn't installed on the machine, we would get COM exceptions. – MagicKat Sep 29 '08 at 22:42
8  
@Geoffrey: ah OK you are going to make me work for it :) --> support.microsoft.com/kb/257757 Microsoft does not currently recommend, and does not support, Automation of Microsoft Office applications from any unattended, non-interactive client application... – Jennifer Zouak Mar 11 '10 at 17:49
2  
I'm coming to this discussion after struggling more than a week on interop, and unless your needs are very simple, this is not gonna work. The support for formatting your spreadsheet is abysmal, which is arguably the reason for generating an .xls file and not just a flat .csv file. For example, have you tried outputting more than 911 characters in a cell, or have you tried setting the width of merged cells in a consistent manner? I have, and I can't tell you how much I hate this crap now... Do yourself a favor and go with one of the free libraries mentioned on this discussion. – md1337 Feb 3 '11 at 18:52
show 5 more comments

You could consider creating your files using the XML Spreadsheet 2003 format. This is a simple XML format using a well documented schema.

share|improve this answer

If you're creating Excel 2007/2010 files give this open source project a try: http://closedxml.codeplex.com

share|improve this answer
4  
I tried using this in a project that builds pretty large Excel sheets. Excellent library, but extremely poor in performance. I just did a comparison for the project I'm working on: ClosedXML (v 0.53.3) took 92,489 ms whereas EPPlus (v 2.9.03, for testing - we can't use because it's GPL) took 16,500 ms. – Druid Jun 8 '11 at 12:40

You may want to take a look at http://www.gemboxsoftware.com/GBSpreadsheetFree.htm.

They have a free version with all features but limited to 150 rows per sheet and 5 sheets per workbook, if that falls within your needs.

I haven't had need to use it myself yet, but does look interesting.

share|improve this answer

The various Office 2003 XML libraries avaliable work pretty well for smaller excel files. However, I find the sheer size of a large workbook saved in the XML format to be a problem. For example, a workbook I work with that would be 40MB in the new (and admittedly more tightly packed) XLSX format becomes a 360MB XML file.

As far as my research has taken me, there are two commercial packages that allow output to the older binary file formats. They are:

Neither are cheap (500USD and 800USD respectively, I think). but both work independant of Excel itself.

What I would be curious about is the Excel output module for the likes of OpenOffice.org. I wonder if they can be ported from Java to .Net.

share|improve this answer
show 1 more comment

I agree about generating XML Spreadsheets, here's an example on how to do it for C# 3 (everyone just blogs about it in VB 9 :P) http://www.aaron-powell.com/linq-to-xml-to-excel

share|improve this answer
show 2 more comments

Here's a completely free C# library, which lets you export from a DataSet, DataTable or List<> into a genuine Excel 2007 .xlsx file, using the OpenXML libraries:

http://www.mikesknowledgebase.com/pages/CSharp/ExportToExcel.htm

Full source code is provided, free of charge, along with instructions, and a demo application.

After adding this class to your application, you can export your DataSet to Excel in just one line of code:

CreateExcelFile.CreateExcelDocument(myDataSet, "C:\\Sample.xlsx");

It doesn't get much simpler than that....

And it doesn't even require Excel to be present on your server.

share|improve this answer
show 2 more comments

I've just recently used FlexCel.NET and found it to be an excellent library! I don't say that about too many software products. No point in giving the whole sales pitch here, you can read all the features on their website.

It is a commercial product, but you get the full source if you buy it. So I suppose you could compile it into your assembly if you really wanted to. Otherwise it's just one extra assembly to xcopy - no configuration or installation or anything like that.

I don't think you'll find any way to do this without third-party libraries as .NET framework, obviously, does not have built in support for it and OLE Automation is just a whole world of pain.

share|improve this answer
show 1 more comment

IKVM + POI

Or, you could use the Interop ...

share|improve this answer
3  
Or you could use the .net port of poi: npoi.codeplex.com – Chris Dec 16 '09 at 22:44

Well,

you can also use a third party library like Aspose.

This library has the benefit that it does not require Excel to be installed on your machine which would be ideal in your case.

share|improve this answer
1  
Yes you can, if you don't mind paying a minimum license fee of $999. Try the MikesKnowledgeBase library... which is $999 cheaper than this !! – Mike Gledhill Jan 5 '12 at 13:10
show 1 more comment

Here's a way to do it with LINQ to XML, complete with sample code:

Quickly Import and Export Excel Data with LINQ to XML

It's a little complex, since you have to import namespaces and so forth, but it does let you avoid any external dependencies.

(Also, of course, it's VB .NET, not C#, but you can always isolate the VB .NET stuff in its own project to use XML Literals, and do everything else in C#.)

share|improve this answer

The Java open source solution is Apache POI. Maybe there is a way to setup interop here, but I don't know enough about Java to answer that.

When I explored this problem I ended up using the Interop assemblies.

share|improve this answer

Have you ever tried sylk?

We used to generate excelsheets in classic asp as sylk and right now we're searching for an excelgenerater too.

The advantages for sylk are, you can format the cells.

share|improve this answer
show 1 more comment

Just want to add another reference to a third party solution that directly addresses your issue: http://www.officewriter.com

(Disclaimer: I work for SoftArtisans, the company that makes OfficeWriter)

share|improve this answer

Some 3rd party component vendors like Infragistics or Syncfusion provide very good Excel export capabilities that do not require Microsoft Excel to be installed.

Since these vendors also provide advanced UI grid components, these components are particularly handy if you want the style and layout of an excel export to mimic the current state of a grid in the user interface of your application.

If your export is intended to be executed server side with emphasis on the data to be exported and with no link to the UI, then I would go for one of the free open source options (e.g. ExcelLibrary).

I have previously been involved with projects that attempted to use server side automation on the Microsoft Office suite. Based on this experience I would strongly recommend against that approach.

share|improve this answer

Look at samples how to create Excel files.

There are examples in C# and VB.NET

It manages XSL XSLX and CSV Excel files.

http://www.devtriogroup.com/ExcelJetcell/Samples

share|improve this answer
2  
Minimum license fee cost: $175. – Mike Gledhill Jan 5 '12 at 13:12
public class GridViewExportUtil
{
    public static void Export(string fileName, GridView gv)
    {
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.AddHeader(
            "content-disposition", string.Format("attachment; filename={0}", fileName));
        HttpContext.Current.Response.ContentType = "application/ms-excel";

        using (StringWriter sw = new StringWriter())
        {
            using (HtmlTextWriter htw = new HtmlTextWriter(sw))
            {
                //  Create a form to contain the grid
                Table table = new Table();

                //  add the header row to the table
                if (gv.HeaderRow != null)
                {
                    GridViewExportUtil.PrepareControlForExport(gv.HeaderRow);
                    table.Rows.Add(gv.HeaderRow);
                }

                //  add each of the data rows to the table
                foreach (GridViewRow row in gv.Rows)
                {
                    GridViewExportUtil.PrepareControlForExport(row);
                    table.Rows.Add(row);
                }

                //  add the footer row to the table
                if (gv.FooterRow != null)
                {
                    GridViewExportUtil.PrepareControlForExport(gv.FooterRow);
                    table.Rows.Add(gv.FooterRow);
                }

                //  render the table into the htmlwriter
                table.RenderControl(htw);

                //  render the htmlwriter into the response
                HttpContext.Current.Response.Write(sw.ToString());
                HttpContext.Current.Response.End();
            }
        }
    }

    /// <summary>
    /// Replace any of the contained controls with literals
    /// </summary>
    /// <param name="control"></param>
    private static void PrepareControlForExport(Control control)
    {
        for (int i = 0; i < control.Controls.Count; i++)
        {
            Control current = control.Controls[i];
            if (current is LinkButton)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
            }
            else if (current is ImageButton)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
            }
            else if (current is HyperLink)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
            }
            else if (current is DropDownList)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
            }
            else if (current is CheckBox)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
            }

            if (current.HasControls())
            {
                GridViewExportUtil.PrepareControlForExport(current);
            }
        }
    }
}

Hi this solution is to export your grid view to your excel file it might help you out

share|improve this answer
show 2 more comments

You can create nicely formatted Excel files using this library: http://officehelper.codeplex.com/documentation
See below sample:

using (ExcelHelper helper = new ExcelHelper(TEMPLATE_FILE_NAME, GENERATED_FILE_NAME))
{
    helper.Direction = ExcelHelper.DirectionType.TOP_TO_DOWN;
    helper.CurrentSheetName = "Sheet1";
    helper.CurrentPosition = new CellRef("C3");

    //the template xlsx should contains the named range "header"; use the command "insert"/"name".
    helper.InsertRange("header");

    //the template xlsx should contains the named range "sample1";
    //inside this range you should have cells with these values:
    //<name> , <value> and <comment>, which will be replaced by the values from the getSample()
    CellRangeTemplate sample1 = helper.CreateCellRangeTemplate("sample1", new List<string> {"name", "value", "comment"}); 
    helper.InsertRange(sample1, getSample());

    //you could use here other named ranges to insert new cells and call InsertRange as many times you want, 
    //it will be copied one after another;
    //even you can change direction or the current cell/sheet before you insert

    //typically you put all your "template ranges" (the names) on the same sheet and then you just delete it
    helper.DeleteSheet("Sheet3");
}        

where sample look like this:

private IEnumerable<List<object>> getSample()
{
    var random = new Random();

    for (int loop = 0; loop < 3000; loop++)
    {
        yield return new List<object> {"test", DateTime.Now.AddDays(random.NextDouble()*100 - 50), loop};
    }
}
share|improve this answer

you can just write it out to XML using the Excel XML format and name it .XLS and it will open with excel. You can control all the formatting (bold, widths, etc) in your XML file heading

http://en.wikipedia.org/wiki/Microsoft_Office_XML_formats#Excel_XML_Spreadsheet_example

share|improve this answer
2  
This is cool except it doesn't support charts or images. – Francois Botha Sep 22 '10 at 16:03

Look for ExtremeML. It's a pretty cool library which enables you to use the OpenXML format for generating OpenXML files.

It's also an OpenSource project.

http://www.extrememl.com/

share|improve this answer
1 2

protected by Praveen May 9 at 10:07

This question is protected to prevent "thanks!", "me too!", or spam answers by new users. To answer it, you must have earned at least 10 reputation on this site.

Not the answer you're looking for? Browse other questions tagged or ask your own question.