232

Is there a free or open source library to read Excel files (.xls) directly from a C# program?

It does not need to be too fancy, just to select a worksheet and read the data as strings. So far, I've been using Export to Unicode text function of Excel, and parsing the resulting (tab-delimited) file, but I'd like to eliminate the manual step.

Chris
  • 6,761
  • 6
  • 52
  • 67
dbkk
  • 12,643
  • 13
  • 53
  • 60

32 Answers32

152
var fileName = string.Format("{0}\\fileNameHere", Directory.GetCurrentDirectory());
var connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; data source={0}; Extended Properties=Excel 8.0;", fileName);

var adapter = new OleDbDataAdapter("SELECT * FROM [workSheetNameHere$]", connectionString);
var ds = new DataSet();

adapter.Fill(ds, "anyNameHere");

DataTable data = ds.Tables["anyNameHere"];

This is what I usually use. It is a little different because I usually stick a AsEnumerable() at the edit of the tables:

var data = ds.Tables["anyNameHere"].AsEnumerable();

as this lets me use LINQ to search and build structs from the fields.

var query = data.Where(x => x.Field<string>("phoneNumber") != string.Empty).Select(x =>
                new MyContact
                    {
                        firstName= x.Field<string>("First Name"),
                        lastName = x.Field<string>("Last Name"),
                        phoneNumber =x.Field<string>("Phone Number"),
                    });
Robin Robinson
  • 1,595
  • 1
  • 20
  • 24
  • If seems like the Select in this approach tries to guess the data type of the column and force upon that guessed data type. For example, if you have a column with mostly double values, it won't like you passing x.Field, but expects x.Field. IS this true? – Kevin Le - Khnle Jun 03 '10 at 14:47
  • 1
    Just looked it up on MSDN. Looks like the is just used to attempt to cast the contents in the column to a type. In this example and just casting the data in the columns to strings. If you wanted a double you would need to call double.Parse(x.Field("Cost") or something like that. Field is an extension method for DataRow and it looks like there aren't an non generic versions. – Robin Robinson Jun 03 '10 at 18:20
  • Does adding a double.Parse to the Linq query slow it down much? – Anonymous Type Dec 19 '10 at 22:06
  • Not that I have noticed. I haven't done any real performance on this. For our uses, it isn't being done a lot. – Robin Robinson Dec 21 '10 at 17:07
  • 23
    Note that if you're reading `xlsx`, you need to use this connection string instead: `string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}; Extended Properties=Excel 12.0;", fileName)` – Andreas Grech Mar 10 '12 at 18:50
  • 7
    Sadly the Jet.OLEDB driver is not 64-bit compatible; you will need to switch to target x86 rather than Any CPU (if you still want to go ahead with this method). Alternatively install the 64-bit ACE driver and change the conn string to use this driver (as indicated by Andreas) - http://www.microsoft.com/en-us/download/details.aspx?displaylang=en&id=13255 – Duncan Jun 06 '12 at 16:04
  • Cannot install the 64 bit ACE driver if the target machine has a 32 bit version of office installed. – Neal Oct 29 '12 at 01:18
  • If this helps anyone, the Jet driver works fine in Win7 64bit... as long as I actually have the document open in Excel. – CodeRedick Jan 14 '13 at 08:00
83

If it is just simple data contained in the Excel file you can read the data via ADO.NET. See the connection strings listed here:

http://www.connectionstrings.com/?carrier=excel2007 or http://www.connectionstrings.com/?carrier=excel

-Ryan

Update: then you can just read the worksheet via something like select * from [Sheet1$]

Ryan Farley
  • 11,315
  • 4
  • 46
  • 43
  • 1
    This way is by far the fastest. – StingyJack Jan 19 '09 at 14:06
  • 17
    Of course that's not true, Stingy. You have to sift through all the data and write crappy DB code (hand craft your models, map columns to properties, yadda yadda). The quickest way is to let *some other poor SOB do this for you*. That's why people use frameworks instead of writing everything from the bottom up. –  Nov 27 '09 at 18:27
  • Besides that I have had times where it didn't give me the right results due to localization problems... the neverending fight of seperators – cyberzed Feb 11 '10 at 13:26
  • 12
    Worthless method! Truncates text columns to 255 characters when read. Beware! See: http://stackoverflow.com/questions/1519288/jet-engine-255-character-truncation ACE engine does same thing! – Triynko May 13 '10 at 18:29
  • Triynko, it has been a super long time since I used this method, but IIRC you can get around the 255 char limit by defining an ODBC DSN for the spreadsheet and then define the columns as longer in length and then use the DSN to connect to the spreadsheet. It's a pain to do that, but I believe that gets around that. – Ryan Farley May 13 '10 at 22:24
  • 5
    Be aware that using ADO.NET to read data from exel requires Microsoft Access or Microsoft Access Database Engine Redistributable installed. – zihotki Jan 05 '11 at 16:43
  • 3
    The driver will also guess at the columns types based on the first several rows. If you have a column with what looks like integers in the first rows you will encounter an error when you hit a non-integer (e.g. a float, a string) – Brian Low Apr 13 '11 at 18:50
  • 1
    This also will not work at ALL if you are running in a 64 bit process. http://forums.asp.net/p/1128266/1781961.aspx – aquinas Sep 23 '11 at 21:19
27

The ADO.NET approach is quick and easy, but it has a few quirks which you should be aware of, especially regarding how DataTypes are handled.

This excellent article will help you avoid some common pitfalls: http://blog.lab49.com/archives/196

Ian Nelson
  • 57,123
  • 20
  • 76
  • 103
22

This is what I used for Excel 2003:

Dictionary<string, string> props = new Dictionary<string, string>();
props["Provider"] = "Microsoft.Jet.OLEDB.4.0";
props["Data Source"] = repFile;
props["Extended Properties"] = "Excel 8.0";

StringBuilder sb = new StringBuilder();
foreach (KeyValuePair<string, string> prop in props)
{
    sb.Append(prop.Key);
    sb.Append('=');
    sb.Append(prop.Value);
    sb.Append(';');
}
string properties = sb.ToString();

using (OleDbConnection conn = new OleDbConnection(properties))
{
    conn.Open();
    DataSet ds = new DataSet();
    string columns = String.Join(",", columnNames.ToArray());
    using (OleDbDataAdapter da = new OleDbDataAdapter(
        "SELECT " + columns + " FROM [" + worksheet + "$]", conn))
    {
        DataTable dt = new DataTable(tableName);
        da.Fill(dt);
        ds.Tables.Add(dt);
    }
}
Dmitry Shechtman
  • 6,548
  • 5
  • 26
  • 25
21

How about Excel Data Reader?

http://exceldatareader.codeplex.com/

I've used in it anger, in a production environment, to pull large amounts of data from a variety of Excel files into SQL Server Compact. It works very well and it's rather robust.

  • 2
    I'll second Excel Data Reader; it has also led to the incredibly useful Excel Data Driven Tests library, which uses NUnit 2.5's TestCaseSource attribute to make data-driven tests using Excel spreadsheets ridiculously easy. Just beware that Resharper doesn't yet support TestCaseSource, so you have to use the NUnit runner. – David Keaveny Oct 20 '10 at 05:14
  • Unfortunately, there are some issues with this library that we've just encountered. Firstly we've had some currency fields coming out as dates. Secondly it is crashing if the workbook has any empty sheets in it. So, although it was very easy to integrate we are now re-evaluating whether to keep using this library. It does not seem to be being actively developed. – Ian1971 Oct 23 '12 at 13:02
  • It also assumes the presence of some optional elements in xlsx file that cause it to fail to read the data if they're absent. – RichieHindle Dec 20 '12 at 12:25
  • We're having problems with Excel files coming from SQL Server Reporting Services. They just don't work, unless you open them and save them (even unedited). @RichieHindle: what optional elements are you talking about (hoping this might help me with my SSRS Excel files)? – Peter Jan 14 '13 at 08:40
  • @Peter: I think it was a missing `` element in the `` that was causing trouble for me. – RichieHindle Jan 14 '13 at 09:12
  • As an update to my comment above. We did keep going with this library, and in fact I and another guy have become developers on the project and it is now actively being worked on again. The issues I mentioned have now been fixed, as has open office support and hopefully SSRS (need someone to test it). – Ian1971 Jan 17 '13 at 12:39
16

Here's some code I wrote in C# using .NET 1.1 a few years ago. Not sure if this would be exactly what you need (and may not be my best code :)).

using System;
using System.Data;
using System.Data.OleDb;

namespace ExportExcelToAccess
{
    /// <summary>
    /// Summary description for ExcelHelper.
    /// </summary>
    public sealed class ExcelHelper
    {
        private const string CONNECTION_STRING = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=<FILENAME>;Extended Properties=\"Excel 8.0;HDR=Yes;\";";

        public static DataTable GetDataTableFromExcelFile(string fullFileName, ref string sheetName)
        {
            OleDbConnection objConnection = new OleDbConnection();
            objConnection = new OleDbConnection(CONNECTION_STRING.Replace("<FILENAME>", fullFileName));
            DataSet dsImport = new DataSet();

            try
            {
                objConnection.Open();

                DataTable dtSchema = objConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

                if( (null == dtSchema) || ( dtSchema.Rows.Count <= 0 ) )
                {
                    //raise exception if needed
                }

                if( (null != sheetName) && (0 != sheetName.Length))
                {
                    if( !CheckIfSheetNameExists(sheetName, dtSchema) )
                    {
                        //raise exception if needed
                    }
                }
                else
                {
                    //Reading the first sheet name from the Excel file.
                    sheetName = dtSchema.Rows[0]["TABLE_NAME"].ToString();
                }

                new OleDbDataAdapter("SELECT * FROM [" + sheetName + "]", objConnection ).Fill(dsImport);
            }
            catch (Exception)
            {
                //raise exception if needed
            }
            finally
            {
                // Clean up.
                if(objConnection != null)
                {
                    objConnection.Close();
                    objConnection.Dispose();
                }
            }


            return dsImport.Tables[0];
            #region Commented code for importing data from CSV file.
            //              string strConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +"Data Source=" + System.IO.Path.GetDirectoryName(fullFileName) +";" +"Extended Properties=\"Text;HDR=YES;FMT=Delimited\"";
            //
            //              System.Data.OleDb.OleDbConnection conText = new System.Data.OleDb.OleDbConnection(strConnectionString);
            //              new System.Data.OleDb.OleDbDataAdapter("SELECT * FROM " + System.IO.Path.GetFileName(fullFileName).Replace(".", "#"), conText).Fill(dsImport);
            //              return dsImport.Tables[0];

            #endregion
        }

        /// <summary>
        /// This method checks if the user entered sheetName exists in the Schema Table
        /// </summary>
        /// <param name="sheetName">Sheet name to be verified</param>
        /// <param name="dtSchema">schema table </param>
        private static bool CheckIfSheetNameExists(string sheetName, DataTable dtSchema)
        {
            foreach(DataRow dataRow in dtSchema.Rows)
            {
                if( sheetName == dataRow["TABLE_NAME"].ToString() )
                {
                    return true;
                }   
            }
            return false;
        }
    }
}
hitec
  • 1,207
  • 4
  • 14
  • 21
  • Couldn't agree more Cherian. This code is many years old... before I even was proficient with Resharper :) – hitec Jul 13 '09 at 17:48
  • 2
    The code is ugly, but it shows how to get the sheet names, great! – Sam Jul 23 '10 at 09:16
15

Koogra is an open-source component written in C# that reads and writes Excel files.

Rune Grimstad
  • 35,612
  • 10
  • 61
  • 76
12

While you did specifically ask for .xls, implying the older file formats, for the OpenXML formats (e.g. xlsx) I highly recommend the OpenXML SDK (http://msdn.microsoft.com/en-us/library/bb448854.aspx)

Hafthor
  • 16,358
  • 9
  • 56
  • 65
8

I did a lot of reading from Excel files in C# a while ago, and we used two approaches:

  • The COM API, where you access Excel's objects directly and manipulate them through methods and properties
  • The ODBC driver that allows to use Excel like a database.

The latter approach was much faster: reading a big table with 20 columns and 200 lines would take 30 seconds via COM, and half a second via ODBC. So I would recommend the database approach if all you need is the data.

Cheers,

Carl

Carl Seleborg
  • 13,125
  • 11
  • 58
  • 70
6

ExcelMapper is an open source tool (http://code.google.com/p/excelmapper/) that can be used to read Excel worksheets as Strongly Typed Objects. It supports both xls and xlsx formats.

6

I want to show a simple method to read xls/xlsx file with .NET. I hope that the following will be helpful for you.

 private DataTable ReadExcelToTable(string path)    
 {

     //Connection String

     string connstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1';";  
     //the same name 
     //string connstring = Provider=Microsoft.JET.OLEDB.4.0;Data Source=" + path + //";Extended Properties='Excel 8.0;HDR=NO;IMEX=1';"; 

     using(OleDbConnection conn = new OleDbConnection(connstring))
     {
        conn.Open();
        //Get All Sheets Name
        DataTable sheetsName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,new object[]{null,null,null,"Table"});  

        //Get the First Sheet Name
        string firstSheetName = sheetsName.Rows[0][2].ToString(); 

        //Query String 
        string sql = string.Format("SELECT * FROM [{0}]",firstSheetName); 
        OleDbDataAdapter ada =new OleDbDataAdapter(sql,connstring);
        DataSet set = new DataSet();
        ada.Fill(set);
        return set.Tables[0];   
   }
 }

Code is from article: http://www.c-sharpcorner.com/uploadfile/d2dcfc/read-excel-file-with-net/. You can get more details from it.

hackp0int
  • 4,052
  • 8
  • 59
  • 95
Lizzy
  • 11
  • 1
  • 1
4

Not free, but with the latest Office there's a very nice automation .Net API. (there has been an API for a long while but was nasty COM) You can do everything you want / need in code all while the Office app remains a hidden background process.

xanadont
  • 7,493
  • 6
  • 36
  • 49
  • 3
    @Anonymous-type I did read the question and was offering a helpful alternative to a desired OSS implementation ... because, well, I was pretty sure there was nothing available. And, judging by the accepted answer, a requirement of having Office installed is not an issue. – xanadont Dec 20 '10 at 20:25
3

SmartXLS is another excel spreadsheet component which support most features of excel Charts,formulas engines, and can read/write the excel2007 openxml format.

liya
  • 782
  • 5
  • 6
3

Forgive me if I am off-base here, but isn't this what the Office PIA's are for?

Rob Cooper
  • 28,567
  • 26
  • 103
  • 142
  • 5
    Yes, but that would involve creating an Excel.Application instance, loading the xls file, etc. If the requirement is purely to read some data from the file then it's much easier and far more lightweight to use one of the ADO.NET methods described in the other answers. – Adam Ralph Jan 19 '09 at 22:28
  • Too slow, using Office PIA as the baseline, everything else is faster - even just using an Object array passed from .Value2 property. Which is still using the PIA. – Anonymous Type Dec 19 '10 at 22:11
3

Lately, partly to get better at LINQ.... I've been using Excel's automation API to save the file as XML Spreadsheet and then get process that file using LINQ to XML.

kenny
  • 21,522
  • 8
  • 49
  • 87
3

SpreadsheetGear for .NET is an Excel compatible spreadsheet component for .NET. You can see what our customers say about performance on the right hand side of our product page. You can try it yourself with the free, fully-functional evaluation.

Joe Erickson
  • 7,077
  • 1
  • 31
  • 31
3

The .NET component Excel Reader .NET may satisfy your requirement. It's good enought for reading XLSX and XLS files. So try it from:

http://www.devtriogroup.com/ExcelReader

2

Late to the party, but I'm a fan of LinqToExcel

DeeDee
  • 2,641
  • 2
  • 17
  • 21
2

You can try using this open source solution that makes dealing with Excel a lot more cleaner.

http://excelwrapperdotnet.codeplex.com/

user289261
  • 41
  • 1
2

SpreadsheetGear is awesome. Yes it's an expense, but compared to twiddling with these other solutions, it's worth the cost. It is fast, reliable, very comprehensive, and I have to say after using this product in my fulltime software job for over a year and a half, their customer support is fantastic!

John R
  • 19
  • 1
2

I recommend the FileHelpers Library which is a free and easy to use .NET library to import/export data from EXCEL, fixed length or delimited records in files, strings or streams + More.

The Excel Data Link Documentation Section http://filehelpers.sourceforge.net/example_exceldatalink.html

Jason Von Ruden
  • 184
  • 1
  • 5
  • 10
  • 1
    I won't down you, but I recently started using FileHelpers and was shocked at how ... crappy it is. For instance, the only way to map columns in a csv to properties... excuse me, FIELDS, of a model is *to create the fields in the order of the columns*. I don't know about you, but I wouldn't rely on a quirk of the compiler for one of the most central design considerations of my f8king framework. –  Nov 27 '09 at 18:31
2

The solution that we used, needed to:

  • Allow Reading/Writing of Excel produced files
  • Be Fast in performance (not like using COMs)
  • Be MS Office Independent (needed to be usable without clients having MS Office installed)
  • Be Free or Open Source (but actively developed)

There are several choices, but we found NPoi (.NET port of Java's long existing Poi open source project) to be the best: http://npoi.codeplex.com/

It also allows working with .doc and .ppt file formats

Marcel Toth
  • 10,716
  • 4
  • 22
  • 17
2

If it's just tabular data. I would recommend file data helpers by Marcos Melli which can be downloaded here.

cless
  • 39
  • 8
1

We use ClosedXML in rather large systems.

  • Free
  • Easy to install
  • Straight forward coding
  • Very responsive support
  • Developer team is extremly open to new suggestions. Often new features and bug fixes are implemented within the same week
Doctor Rudolf
  • 332
  • 2
  • 5
1

Excel Package is an open-source (GPL) component for reading/writing Excel 2007 files. I used it on a small project, and the API is straightforward. Works with XLSX only (Excel 200&), not with XLS.

The source code also seems well-organized and easy to get around (if you need to expand functionality or fix minor issues as I did).

At first, I tried the ADO.Net (Excel connection string) approach, but it was fraught with nasty hacks -- for instance if second row contains a number, it will return ints for all fields in the column below and quietly drop any data that doesn't fit.

dbkk
  • 12,643
  • 13
  • 53
  • 60
1

you could write an excel spreadsheet that loads a given excel spreadsheet and saves it as csv (rather than doing it manually).

then you could automate that from c#.

and once its in csv, the c# program can grok that.

(also, if someone asks you to program in excel, it's best to pretend you don't know how)

(edit: ah yes, rob and ryan are both right)

Leon Bambrick
  • 26,009
  • 9
  • 51
  • 75
1

I know that people have been making an Excel "extension" for this purpose.
You more or less make a button in Excel that says "Export to Program X", and then export and send off the data in a format the program can read.

http://msdn.microsoft.com/en-us/library/ms186213.aspx should be a good place to start.

Good luck

Lars Mæhlum
  • 6,074
  • 3
  • 28
  • 32
1

Just did a quick demo project that required managing some excel files. The .NET component from GemBox software was adequate for my needs. It has a free version with a few limitations.

http://www.gemboxsoftware.com/GBSpreadsheet.htm

Christian Hagelid
  • 8,275
  • 4
  • 40
  • 63
1

Take.io Spreadsheet will do this work for you, and at no charge. Just take a look at this.

greeness
  • 15,956
  • 5
  • 50
  • 80
Balena
  • 1
  • 1
  • This is a really great little library. It just converts everything into Lists of Lists of strings, which is just fine for the kind of work I needed it for. – Drewmate Nov 28 '12 at 23:24
0

I just used ExcelLibrary to load an .xls spreadsheet into a DataSet. Worked great for me.

Hafthor
  • 16,358
  • 9
  • 56
  • 65
0

Excel Data Reader is the way to go!

It´s Open Source, at http://exceldatareader.codeplex.com/ and actively developed.

We been using it for reading Tabular (and sometimes not so tabular) worksheets for a couple of years now (In a financial application).

Works like a charm to read unit test data from human-readable sheets.

Just avoid the feature of trying to return DateTime's, as, for Excel, DateTime's are just double numbers.

JP Negri
  • 1
  • 1
  • 1
    There is already mention of exceldatareader here http://stackoverflow.com/questions/15828/reading-excel-files-from-c/3665991#3665991 .Why do you think we need another answer. You should comment the link, not to create long thread garbage – nemke Feb 06 '11 at 13:26
0

If you have multiple tables in the same worksheet you can give each table an object name and read the table using the OleDb method as shown here: http://vbktech.wordpress.com/2011/05/10/c-net-reading-and-writing-to-multiple-tables-in-the-same-microsoft-excel-worksheet/

VBK
  • 91
  • 1
  • 5