views:

23139

answers:

17

In one of our ASP.NET applications in C#, we take a certain data collection (SubSonic collection) and export it to Excel. We also want to import Excel files in a specific format. I'm looking for a library I can use for this purpose.

Requirements: - Excel 2007 files (Does Excel 2003 support over 64k rows? I need more than that.) - Does not require Excel on the server - Takes a typed collection and, if it can, tries to put numeric fields as numeric in Excel. - Works well with large files (100k to 10M) - fast enough. - Doesn't crash when exporting GUIDs! - Does not cost a crapload of money (no enterprise library like aspose). Free is always great, but can be a commercial library.

What library do you recommend? Have you used it for large quantities of data? Are there other solutions?

Right now, I am using a simple tool that generates HTML that is loaded by Excel later on, but I am losing some capabilities, plus Excel complains when we load it. I don't need to generate charts or anything like that, just export raw data.

I am thinking of flat CSV files, but Excel is a customer requirement. I can work with CSV directly, if I had a tool to convert to and from Excel. Given Excel 2007 is an xml-based (and zipped) file format, I am guessing this kind of library should be easy to find. However, what matters most to me are your comments and opinions.


EDIT: Ironically, in my opinion and following the answer with the most votes, the best Excel import&export library is no export at all. This is not the case for all scenarios, but it is for mine. XLS files support only 64k rows. XLSX supports up to 1M. The free libraries that I've tried feature bad performance (one second to load one row when you have 200k rows). I haven't tried the paid ones, as I feel they are overpriced for the value they deliver when all you need is a fast XLSX<->CSV conversion routine.

A: 

Check the ExcelPackage project, it uses the Office Open XML file format of Excel 2007, it's lightweight and open source...

CMS
Looked good but one comment says it is bad with large files (my scenario)
Jason Kealey
Interesting - it is licensed as GPL, not LGPL. Therefore, it must be used in GPL applications. (Also, unfortunate that development seems to have stopped.)
Jason Kealey
I tried ExcelPackage, but had to abandon it - it fails when you try put single quotes (') in a cell.
Igor Brejc
+2  A: 

I've used Flexcel in the past and it was great. But this was more for programmatically creating and updating excel worksheets.

Duncan
I can't see that this supports Excel 2007 (xlsx). As xls only supports 64k rows, this is a limitation for me.
Jason Kealey
@Jason Kealey - Flexcel does now support Excel 2007 and 2010.
Pauk
A: 

There's a pretty good article and library on CodeProject by Yogesh Jagota:

Excel XML Import-Export Library

I've used it to export data from SQL queries and other data sources to Excel - works just fine for me.

Cheers, Marc

marc_s
Interesting, but requires XML files. Can't read/write xls or xlsx files.
Jason Kealey
+6  A: 

I'm going to throw my hand in for flat csv files, if only because you've got the greatest control over the code. Just make sure that you read in the rows and process them one at a time (reading the document to the end and splitting will eat up all of your memory - same with writing, stream it out).

Yes, the user will have to save-as CSV in excel before you can process it, but perhaps this limitation can be overcome by training and providing clear instructions on the page?

Finally, when you export to the customer, if you set the mime type to text/csv, Excel is usually mapped to that type so it appears to the user to be 'an Excel file'.

Travis
I agree, but in my case it would be good to support xls(x) files directly. However, do you know of any csv <-> xls(x) tools?
Jason Kealey
No, I've never needed to do xls. Sorry :-/
Travis
I tried CSV approach too, but there are several issues with it. For example, what if you want to have a multi-line text in a cell? I couldn't make Excel import such a CSV.
Igor Brejc
Actually, you can have mult-line text in a CSV file. Just try this as your file contents: cell 1,"this\nis\nmultiline",cell 3
Chris
CSV has its place but the poster asked about Excel, I assume that he must want Excel, not CSV.
John Scipione
CSV falls down when exporting columns like 0345. Excel automatically trims this out to 345. Which is not at all helpful when that leading digit is important.
Chris Lively
+3  A: 

Although it's not a library, I have used this method for a GridView based on this article.

Example to export a grid to Excel 2003, have not tried it for Excel 2007 yet:

        private void ExportGv()
        {
            Response.Clear();
            Response.AddHeader("content-disposition",
                string.Format("attachment;filename={0}.xls", "ToExcel.xls"));
            Response.Charset = "iso-8859-1";
            Response.ContentType = "application/vnd.xls";


            StringWriter stringWrite = new StringWriter();
            HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

            gvGrid.RenderControl(htmlWrite);

            Response.Write(stringWrite.ToString());
            Response.End();
        }
    /// <summary>
    /// Hack to allow renderControl
    /// http://aspnet.4guysfromrolla.com/articles/122006-1.aspx#postadlink
    /// and
    /// http://blogs.x2line.com/al/archive/2004/10/08/576.aspx
    /// </summary>
    /// <param name="control"></param>
    public override void VerifyRenderingInServerForm(Control control)
    {
        return;
    }

   /// You would also need a click event to set bToExcel=true <br/>

    protected override void Render(HtmlTextWriter writer)
    {
        if (bToExcel)
            ExportGv();

        bToExcel = false;

        base.Render(writer);
    }
Kb
This actually renders html and puts an xls extension on the end. Excel then interprets the data as a table. You are not generating a real Excel file.
ck
2007 introduced "MIME type hardening" that will throw up a warning to the user if you use this method where the content and file extension don't match. I wouldn't recommend it.
DancesWithBamboo
I had to upvote @ck's comment because I once spent a *ridiculous* amount of time (like half a day) troubleshooting an issue with data that I downloaded from a website with the .xls extension that ended up just being HTML.
Dan Tao
+2  A: 

CSV export is simple, easy to implement, and fast. There is one potential issue worth noting, though. Excel (up to 2007) does not preserve leading zeros in CSV files. This will garble ZIP codes, product ids, and other textual data containing numeric values. There is one trick that will make Excel import the values correctly (using delimiters and prefix values with the = sign, if I remember correctly, e.g. ..,="02052",...). If you have users who will do post-processing tasks with the CSV, they need to be aware that they need to change the format to XLS and not save the file back to CSV. If they do, leading zeros will be lost for good.

cdonner
+11  A: 

I discovered the Open XML SDK since my original answer. It provides strongly typed classes for spreadsheet objects, among other things, and seems to be fairly easy to work with. I am going to use it for reports in one of my projects. Alas, version 2.0 is not supposed to get released until late 2009 or 2010.

cdonner
Very interesting! Have you tested it using large quantities of data?
Jason Kealey
I have not done any performance test. I will mostly charts and and single-page reports, so throughput is not an issue for me. It appears to be as fast as managed code can be, though.
cdonner
@Jason Kealey: this is really the best answer on this post - export becomes irrelevant with SpreadsheetML. The data is all accessible from within the file. If you need the data in a different format, provide a transform via an XSLT or via Linq.
Otaku
A: 

You can use "Microsoft.Jet.OLEDB.4.0". Regards

RG
One of my requirements is not to have Excel running on the server.
Jason Kealey
A: 

You need a database, like ms sql. Excel is in client side. Am I wrong? I have used this kind of solution in my company.

Regards RG

RG
+2  A: 

SpreadsheetGear for .NET reads and writes CSV / XLS / XLSX and does more.

You can see live ASP.NET samples with C# and VB source code here and download a free trial here.

Of course I think SpreadsheetGear is the best library to import / export Excel workbooks in ASP.NET - but I am biased. You can see what some of our customers say on the right hand side of this page.

Disclaimer: I own SpreadsheetGear LLC

Joe Erickson
+3  A: 

NPOI For Excel 2003 Open Source http://www.leniel.net/2009/07/creating-excel-spreadsheets-xls-xlsx-c.html

stormwild
I used this library the other day looking into this issue. It is an excellent library!
Dillie-O
A: 

For years, I have used JExcel for this (http://jexcelapi.sourceforge.com), an excellent open-source Java project. It was also .NET-able by using J# to compile it, and I have also had great success with it in this incarnation. However, recently I needed to migrate the code to native .NET to support a 64-bit IIS application in which I create Excel output. The 32-bit J# version would not load.

The code for CSharpJExcel is LGPL and is available currently at http://www.chrislaforetsoftware.com/products.html while we prepare to deploy it on the JExcel SourceForge site. It will compile with VS2005 or VS2008. The examples in the original JExcel documentation will pretty well move over intact to the .NET version.

Hope it is helpful to someone out here.

-Chris

Chris Laforet
+1  A: 

the new version of ExcelPackage is here EPPlus.codeplex.com

I'm still fighting with the export to excel function since my application should export some data to excel-template 2007

this project seems fine to me, and the developer is very responsive to bugs and issues.

Mohannad Otaibi
A: 

I use a best tool for importing and exporting Excel Spreadsheet with .net, it can reading and writing to excel 97 ~ 2010 from c#, extremely easy to use, I use it long time quit good.

Peter
A: 

Spreadsheetgear is the best commercial library we have found and are using. Our company does a lot of advanced excel import and export and Spreadsheetgear supports lots of advanced excel features far beyond anything you can do with simple CSV, and it's fast. It isn't free or very cheap though but worth it because the support is excellent. The developers will actually respond to you if you run into an issue.

pilavdzice
A: 

I've tried CSharpJExcel and wouldn't recommend it, at least not until there is some documentation available. Contrary to the developers comments it is not a straight native port.

A: 

How about the apache POI java library. I havent used it for Excel , but did use it for Word 2007.

harijay