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

<p>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.</p>

[{'answer_id': 15835, 'author': 'Leon Bambrick', 'author_id': 49, 'author_profile': 'https://Stackoverflow.com/users/49', 'pm_score': 1, 'selected': False, 'text': "<p>you could write an excel spreadsheet that loads a given excel spreadsheet and saves it as csv (rather than doing it manually).</p>\n\n<p>then you could automate that from c#.</p>\n\n<p>and once its in csv, the c# program can grok that.</p>\n\n<p>(also, if someone asks you to program in excel, it's best to pretend you don't know how)</p>\n\n<p>(edit: ah yes, rob and ryan are both right)</p>\n"}, {'answer_id': 15836, 'author': 'Lars Mæhlum', 'author_id': 960, 'author_profile': 'https://Stackoverflow.com/users/960', 'pm_score': 1, 'selected': False, 'text': '<p>I know that people have been making an Excel "extension" for this purpose.<br>\nYou 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.</p>\n\n<p><a href="http://msdn.microsoft.com/en-us/library/ms186213.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms186213.aspx</a> should be a good place to start.</p>\n\n<p>Good luck</p>\n'}, {'answer_id': 15837, 'author': 'Rob Cooper', 'author_id': 832, 'author_profile': 'https://Stackoverflow.com/users/832', 'pm_score': 2, 'selected': False, 'text': '<p>Forgive me if I am off-base here, but isn\'t this what the <a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=C41BD61E-3060-4F71-A6B4-01FEBA508E52&amp;displaylang=en" rel="nofollow noreferrer">Office PIA\'s</a> are for?</p>\n'}, {'answer_id': 15839, 'author': 'Ryan Farley', 'author_id': 1627, 'author_profile': 'https://Stackoverflow.com/users/1627', 'pm_score': 6, 'selected': False, 'text': '<p>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:</p>\n\n<p><a href="http://www.connectionstrings.com/?carrier=excel2007" rel="noreferrer">http://www.connectionstrings.com/?carrier=excel2007</a>\nor \n<a href="http://www.connectionstrings.com/?carrier=excel2007" rel="noreferrer">http://www.connectionstrings.com/?carrier=excel</a></p>\n\n<p>-Ryan</p>\n\n<p>Update: then you can just read the worksheet via something like <code>select * from [Sheet1$]</code></p>\n'}, {'answer_id': 15842, 'author': 'xanadont', 'author_id': 1886, 'author_profile': 'https://Stackoverflow.com/users/1886', 'pm_score': 2, 'selected': False, 'text': "<p>Not free, but with the latest Office there's a <em>very</em> 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.</p>\n"}, {'answer_id': 15858, 'author': 'Christian Hagelid', 'author_id': 202, 'author_profile': 'https://Stackoverflow.com/users/202', 'pm_score': 1, 'selected': False, 'text': '<p>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.</p>\n\n<p><a href="http://www.gemboxsoftware.com/GBSpreadsheet.htm" rel="nofollow noreferrer">http://www.gemboxsoftware.com/GBSpreadsheet.htm</a></p>\n'}, {'answer_id': 15970, 'author': 'hitec', 'author_id': 120, 'author_profile': 'https://Stackoverflow.com/users/120', 'pm_score': 4, 'selected': False, 'text': '<p>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 :)).</p>\n\n<pre><code>using System;\nusing System.Data;\nusing System.Data.OleDb;\n\nnamespace ExportExcelToAccess\n{\n    /// &lt;summary&gt;\n    /// Summary description for ExcelHelper.\n    /// &lt;/summary&gt;\n    public sealed class ExcelHelper\n    {\n        private const string CONNECTION_STRING = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=&lt;FILENAME&gt;;Extended Properties=\\"Excel 8.0;HDR=Yes;\\";";\n\n        public static DataTable GetDataTableFromExcelFile(string fullFileName, ref string sheetName)\n        {\n            OleDbConnection objConnection = new OleDbConnection();\n            objConnection = new OleDbConnection(CONNECTION_STRING.Replace("&lt;FILENAME&gt;", fullFileName));\n            DataSet dsImport = new DataSet();\n\n            try\n            {\n                objConnection.Open();\n\n                DataTable dtSchema = objConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);\n\n                if( (null == dtSchema) || ( dtSchema.Rows.Count &lt;= 0 ) )\n                {\n                    //raise exception if needed\n                }\n\n                if( (null != sheetName) &amp;&amp; (0 != sheetName.Length))\n                {\n                    if( !CheckIfSheetNameExists(sheetName, dtSchema) )\n                    {\n                        //raise exception if needed\n                    }\n                }\n                else\n                {\n                    //Reading the first sheet name from the Excel file.\n                    sheetName = dtSchema.Rows[0]["TABLE_NAME"].ToString();\n                }\n\n                new OleDbDataAdapter("SELECT * FROM [" + sheetName + "]", objConnection ).Fill(dsImport);\n            }\n            catch (Exception)\n            {\n                //raise exception if needed\n            }\n            finally\n            {\n                // Clean up.\n                if(objConnection != null)\n                {\n                    objConnection.Close();\n                    objConnection.Dispose();\n                }\n            }\n\n\n            return dsImport.Tables[0];\n            #region Commented code for importing data from CSV file.\n            //              string strConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +"Data Source=" + System.IO.Path.GetDirectoryName(fullFileName) +";" +"Extended Properties=\\"Text;HDR=YES;FMT=Delimited\\"";\n            //\n            //              System.Data.OleDb.OleDbConnection conText = new System.Data.OleDb.OleDbConnection(strConnectionString);\n            //              new System.Data.OleDb.OleDbDataAdapter("SELECT * FROM " + System.IO.Path.GetFileName(fullFileName).Replace(".", "#"), conText).Fill(dsImport);\n            //              return dsImport.Tables[0];\n\n            #endregion\n        }\n\n        /// &lt;summary&gt;\n        /// This method checks if the user entered sheetName exists in the Schema Table\n        /// &lt;/summary&gt;\n        /// &lt;param name="sheetName"&gt;Sheet name to be verified&lt;/param&gt;\n        /// &lt;param name="dtSchema"&gt;schema table &lt;/param&gt;\n        private static bool CheckIfSheetNameExists(string sheetName, DataTable dtSchema)\n        {\n            foreach(DataRow dataRow in dtSchema.Rows)\n            {\n                if( sheetName == dataRow["TABLE_NAME"].ToString() )\n                {\n                    return true;\n                }   \n            }\n            return false;\n        }\n    }\n}\n</code></pre>\n'}, {'answer_id': 16051, 'author': 'Robin Robinson', 'author_id': 1629, 'author_profile': 'https://Stackoverflow.com/users/1629', 'pm_score': 8, 'selected': True, 'text': '<pre><code>var fileName = string.Format("{0}\\\\fileNameHere", Directory.GetCurrentDirectory());\nvar connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; data source={0}; Extended Properties=Excel 8.0;", fileName);\n\nvar adapter = new OleDbDataAdapter("SELECT * FROM [workSheetNameHere$]", connectionString);\nvar ds = new DataSet();\n\nadapter.Fill(ds, "anyNameHere");\n\nDataTable data = ds.Tables["anyNameHere"];\n</code></pre>\n\n<p>This is what I usually use.  It is a little different because I usually stick a AsEnumerable() at the edit of the tables: </p>\n\n<pre><code>var data = ds.Tables["anyNameHere"].AsEnumerable();\n</code></pre>\n\n<p>as this lets me use LINQ to search and build structs from the fields.</p>\n\n<pre><code>var query = data.Where(x =&gt; x.Field&lt;string&gt;("phoneNumber") != string.Empty).Select(x =&gt;\n                new MyContact\n                    {\n                        firstName= x.Field&lt;string&gt;("First Name"),\n                        lastName = x.Field&lt;string&gt;("Last Name"),\n                        phoneNumber =x.Field&lt;string&gt;("Phone Number"),\n                    });\n</code></pre>\n'}, {'answer_id': 17921, 'author': 'Ian Nelson', 'author_id': 2084, 'author_profile': 'https://Stackoverflow.com/users/2084', 'pm_score': 5, 'selected': False, 'text': '<p>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.</p>\n\n<p>This excellent article will help you avoid some common pitfalls:\n<a href="http://blog.lab49.com/archives/196" rel="noreferrer">http://blog.lab49.com/archives/196</a></p>\n'}, {'answer_id': 17930, 'author': 'Carl Seleborg', 'author_id': 2095, 'author_profile': 'https://Stackoverflow.com/users/2095', 'pm_score': 3, 'selected': False, 'text': "<p>I did a lot of reading from Excel files in C# a while ago, and we used two approaches:</p>\n\n<ul>\n<li>The COM API, where you access Excel's objects directly and manipulate them through methods and properties</li>\n<li>The ODBC driver that allows to use Excel like a database.</li>\n</ul>\n\n<p>The latter approach was <strong>much</strong> 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.</p>\n\n<p>Cheers,</p>\n\n<p>Carl</p>\n"}, {'answer_id': 43236, 'author': 'Hafthor', 'author_id': 4489, 'author_profile': 'https://Stackoverflow.com/users/4489', 'pm_score': 4, 'selected': False, 'text': '<p>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 (<a href="http://msdn.microsoft.com/en-us/library/bb448854.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/bb448854.aspx</a>)</p>\n'}, {'answer_id': 43451, 'author': 'Jason Von Ruden', 'author_id': 2062, 'author_profile': 'https://Stackoverflow.com/users/2062', 'pm_score': 2, 'selected': False, 'text': '<p>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.</p>\n\n<p><strong>The Excel Data Link Documentation Section</strong>\n<a href="http://filehelpers.sourceforge.net/example_exceldatalink.html" rel="nofollow noreferrer">http://filehelpers.sourceforge.net/example_exceldatalink.html</a></p>\n'}, {'answer_id': 43494, 'author': 'kenny', 'author_id': 3225, 'author_profile': 'https://Stackoverflow.com/users/3225', 'pm_score': 2, 'selected': False, 'text': "<p>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. </p>\n"}, {'answer_id': 43534, 'author': 'Dmitry Shechtman', 'author_id': 3583, 'author_profile': 'https://Stackoverflow.com/users/3583', 'pm_score': 5, 'selected': False, 'text': '<p>This is what I used for Excel 2003:</p>\n\n<pre><code>Dictionary&lt;string, string&gt; props = new Dictionary&lt;string, string&gt;();\nprops["Provider"] = "Microsoft.Jet.OLEDB.4.0";\nprops["Data Source"] = repFile;\nprops["Extended Properties"] = "Excel 8.0";\n\nStringBuilder sb = new StringBuilder();\nforeach (KeyValuePair&lt;string, string&gt; prop in props)\n{\n    sb.Append(prop.Key);\n    sb.Append(\'=\');\n    sb.Append(prop.Value);\n    sb.Append(\';\');\n}\nstring properties = sb.ToString();\n\nusing (OleDbConnection conn = new OleDbConnection(properties))\n{\n    conn.Open();\n    DataSet ds = new DataSet();\n    string columns = String.Join(",", columnNames.ToArray());\n    using (OleDbDataAdapter da = new OleDbDataAdapter(\n        "SELECT " + columns + " FROM [" + worksheet + "$]", conn))\n    {\n        DataTable dt = new DataTable(tableName);\n        da.Fill(dt);\n        ds.Tables.Add(dt);\n    }\n}\n</code></pre>\n'}, {'answer_id': 261566, 'author': 'Rune Grimstad', 'author_id': 30366, 'author_profile': 'https://Stackoverflow.com/users/30366', 'pm_score': 4, 'selected': False, 'text': '<p><a href="http://koogra.sourceforge.net/" rel="nofollow noreferrer">Koogra</a> is an open-source component written in C# that reads and writes Excel files.</p>\n'}, {'answer_id': 458051, 'author': 'Joe Erickson', 'author_id': 56710, 'author_profile': 'https://Stackoverflow.com/users/56710', 'pm_score': 2, 'selected': False, 'text': '<p><a href="http://www.spreadsheetgear.com/" rel="nofollow noreferrer">SpreadsheetGear for .NET</a> is an Excel compatible spreadsheet component for .NET. You can see what our customers say about performance on the right hand side of our <a href="http://www.spreadsheetgear.com/products/spreadsheetgear.net.aspx" rel="nofollow noreferrer">product page</a>. You can try it yourself with the free, fully-functional <a href="https://www.spreadsheetgear.com/downloads/register.aspx" rel="nofollow noreferrer">evaluation</a>.</p>\n'}, {'answer_id': 848634, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>ExcelMapper is an open source tool (<a href="http://code.google.com/p/excelmapper/" rel="noreferrer">http://code.google.com/p/excelmapper/</a>) that can be used to read Excel worksheets as Strongly Typed Objects. It supports both xls and xlsx formats.</p>\n'}, {'answer_id': 1320733, 'author': 'Hafthor', 'author_id': 4489, 'author_profile': 'https://Stackoverflow.com/users/4489', 'pm_score': 0, 'selected': False, 'text': '<p>I just used <a href="http://code.google.com/p/excellibrary/" rel="nofollow noreferrer">ExcelLibrary</a> to load an .xls spreadsheet into a DataSet. Worked great for me.</p>\n'}, {'answer_id': 1495949, 'author': 'liya', 'author_id': 121735, 'author_profile': 'https://Stackoverflow.com/users/121735', 'pm_score': 2, 'selected': False, 'text': '<p><a href="http://www.smartxls.com" rel="nofollow noreferrer">SmartXLS</a> is another excel spreadsheet component which support most features of excel Charts,formulas engines, and can read/write the excel2007 openxml format.</p>\n'}, {'answer_id': 1501792, 'author': 'dbkk', 'author_id': 838, 'author_profile': 'https://Stackoverflow.com/users/838', 'pm_score': 1, 'selected': False, 'text': '<p><a href="http://excelpackage.codeplex.com/" rel="nofollow noreferrer">Excel Package</a> 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&amp;), not with XLS.</p>\n\n<p>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).</p>\n\n<p>At first, I tried the ADO.Net (Excel connection string) approach, but it was fraught with nasty hacks -- for instance if <em>second</em> row contains a number, it will return ints for all fields in the column below and quietly drop any data that doesn\'t fit.</p>\n'}, {'answer_id': 2405759, 'author': 'user289261', 'author_id': 289261, 'author_profile': 'https://Stackoverflow.com/users/289261', 'pm_score': 2, 'selected': False, 'text': '<p>You can try using this open source solution that makes dealing with Excel a lot more cleaner.</p>\n\n<p><a href="http://excelwrapperdotnet.codeplex.com/" rel="nofollow noreferrer">http://excelwrapperdotnet.codeplex.com/</a></p>\n'}, {'answer_id': 3578025, 'author': 'John R', 'author_id': 432177, 'author_profile': 'https://Stackoverflow.com/users/432177', 'pm_score': 2, 'selected': False, 'text': "<p>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!</p>\n"}, {'answer_id': 3665991, 'author': 'Michał Pawłowski', 'author_id': 287737, 'author_profile': 'https://Stackoverflow.com/users/287737', 'pm_score': 4, 'selected': False, 'text': '<p>How about Excel Data Reader? </p>\n\n<p><a href="http://exceldatareader.codeplex.com/" rel="noreferrer">http://exceldatareader.codeplex.com/</a></p>\n\n<p>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.</p>\n'}, {'answer_id': 4902204, 'author': 'JP Negri', 'author_id': 316958, 'author_profile': 'https://Stackoverflow.com/users/316958', 'pm_score': 0, 'selected': False, 'text': '<p>Excel Data Reader is the way to go!</p>\n\n<p>It´s Open Source, at <a href="http://exceldatareader.codeplex.com/" rel="nofollow">http://exceldatareader.codeplex.com/</a> and actively developed.</p>\n\n<p>We been using it for reading Tabular (and sometimes not so tabular) worksheets for a couple of years now (In a financial application).</p>\n\n<p>Works like a charm to  read unit test data from human-readable sheets.</p>\n\n<p>Just avoid the feature of trying to return DateTime\'s, as, for Excel, DateTime\'s are just double numbers.</p>\n'}, {'answer_id': 5631836, 'author': 'Bonnie Cornell', 'author_id': 703481, 'author_profile': 'https://Stackoverflow.com/users/703481', 'pm_score': 2, 'selected': False, 'text': '<p>The .NET component Excel Reader .NET may satisfy your requirement. It\'s good enought for reading XLSX and XLS files. So try it from:</p>\n\n<blockquote>\n  <p><a href="http://www.devtriogroup.com/ExcelReader/Default.aspx" rel="nofollow">http://www.devtriogroup.com/ExcelReader</a></p>\n</blockquote>\n'}, {'answer_id': 5742568, 'author': 'Marcel Toth', 'author_id': 702199, 'author_profile': 'https://Stackoverflow.com/users/702199', 'pm_score': 2, 'selected': False, 'text': '<p>The solution that we used, needed to:</p>\n\n<ul>\n<li>Allow <strong>Reading/Writing</strong> of Excel produced files</li>\n<li>Be <strong>Fast</strong> in performance (not like using COMs)</li>\n<li>Be MS Office <strong>Independent</strong> (needed to be usable without clients having MS Office installed)</li>\n<li>Be <strong>Free</strong> or <strong>Open Source</strong> (but actively developed)</li>\n</ul>\n\n<p>There are several choices, but we found <strong>NPoi</strong> (.NET port of Java\'s long existing <strong>Poi</strong> open source project) to be the best:\n<a href="http://npoi.codeplex.com/" rel="nofollow">http://npoi.codeplex.com/</a></p>\n\n<p>It also allows working with .doc and .ppt file formats</p>\n'}, {'answer_id': 6756362, 'author': 'VBK', 'author_id': 853096, 'author_profile': 'https://Stackoverflow.com/users/853096', 'pm_score': 0, 'selected': False, 'text': '<p>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: <a href="http://vbktech.wordpress.com/2011/05/10/c-net-reading-and-writing-to-multiple-tables-in-the-same-microsoft-excel-worksheet/" rel="nofollow">http://vbktech.wordpress.com/2011/05/10/c-net-reading-and-writing-to-multiple-tables-in-the-same-microsoft-excel-worksheet/</a></p>\n'}, {'answer_id': 7396934, 'author': 'cless', 'author_id': 126624, 'author_profile': 'https://Stackoverflow.com/users/126624', 'pm_score': 2, 'selected': False, 'text': '<p>If it\'s just tabular data. I would recommend file data helpers by Marcos Melli which can be downloaded <a href="http://filehelpers.sourceforge.net/" rel="nofollow">here</a>.</p>\n'}, {'answer_id': 7425567, 'author': 'Balena', 'author_id': 945938, 'author_profile': 'https://Stackoverflow.com/users/945938', 'pm_score': 1, 'selected': False, 'text': '<p><code>Take.io</code> Spreadsheet will do this work for you, and at no charge. Just take a look at <a href="https://bitbucket.org/guibv/takeio.spreadsheet/" rel="nofollow">this</a>.</p>\n'}, {'answer_id': 9580450, 'author': 'Lizzy', 'author_id': 1242112, 'author_profile': 'https://Stackoverflow.com/users/1242112', 'pm_score': 3, 'selected': False, 'text': '<p>I want to show a simple method to read xls/xlsx file with .NET. I hope that the following will be helpful for you.</p>\n\n<pre>\n private DataTable ReadExcelToTable(string path)    \n {\n\n     //Connection String\n\n     string connstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\'Excel 8.0;HDR=NO;IMEX=1\';";  \n     //the same name \n     //string connstring = Provider=Microsoft.JET.OLEDB.4.0;Data Source=" + path + //";Extended Properties=\'Excel 8.0;HDR=NO;IMEX=1\';"; \n\n     using(OleDbConnection conn = new OleDbConnection(connstring))\n     {\n        conn.Open();\n        //Get All Sheets Name\n        DataTable sheetsName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,new object[]{null,null,null,"Table"});  \n\n        //Get the First Sheet Name\n        string firstSheetName = sheetsName.Rows[0][2].ToString(); \n\n        //Query String \n        string sql = string.Format("SELECT * FROM [{0}]",firstSheetName); \n        OleDbDataAdapter ada =new OleDbDataAdapter(sql,connstring);\n        DataSet set = new DataSet();\n        ada.Fill(set);\n        return set.Tables[0];   \n   }\n }</pre>\n\n<p>Code is from article: <a href="http://www.c-sharpcorner.com/uploadfile/d2dcfc/read-excel-file-with-net/" rel="nofollow noreferrer">http://www.c-sharpcorner.com/uploadfile/d2dcfc/read-excel-file-with-net/</a>. You can get more details from it.</p>\n'}, {'answer_id': 12002438, 'author': 'Doctor Rudolf', 'author_id': 563688, 'author_profile': 'https://Stackoverflow.com/users/563688', 'pm_score': 1, 'selected': False, 'text': '<p>We use <a href="http://closedxml.codeplex.com/" rel="nofollow">ClosedXML</a> in rather large systems.</p>\n\n<ul>\n<li>Free</li>\n<li>Easy to install</li>\n<li>Straight forward coding</li>\n<li><strong>Very</strong> responsive support</li>\n<li>Developer team is <strong>extremly</strong> open to new suggestions. Often new features and bug fixes are implemented within the same week</li>\n</ul>\n'}, {'answer_id': 13089551, 'author': 'DeeDee', 'author_id': 646628, 'author_profile': 'https://Stackoverflow.com/users/646628', 'pm_score': 2, 'selected': False, 'text': '<p>Late to the party, but I\'m a fan of <a href="http://code.google.com/p/linqtoexcel/" rel="nofollow">LinqToExcel</a></p>\n'}]
['https://Stackoverflow.com/questions/15828', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/838/']