Skip to main content

Reading Excel files from C#


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.


Source: Tips4allCCNA FINAL EXAM

Comments

  1. 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"),
    });

    ReplyDelete
  2. 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

    ReplyDelete
  3. 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);
    }
    }

    ReplyDelete
  4. 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.

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

    ReplyDelete
  6. 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;
    }
    }
    }

    ReplyDelete
  7. 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

    ReplyDelete
  8. 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.

    ReplyDelete
  9. 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

    ReplyDelete
  10. 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.

    ReplyDelete
  11. 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.

    ReplyDelete
  12. 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.

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

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

    ReplyDelete
  15. 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

    ReplyDelete
  16. 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.

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

    http://excelwrapperdotnet.codeplex.com/

    ReplyDelete
  18. 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!

    ReplyDelete
  19. 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

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

    ReplyDelete
  21. 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)

    ReplyDelete
  22. 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

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

    ReplyDelete
  24. 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/

    ReplyDelete
  25. Take.io Spreadsheet will do this work for you, and at no charge. Just take a look at https://bitbucket.org/guibv/takeio.spreadsheet/.

    ReplyDelete

Post a Comment

Popular posts from this blog

[韓日関係] 首相含む大幅な内閣改造の可能性…早ければ来月10日ごろ=韓国

div not scrolling properly with slimScroll plugin

I am using the slimScroll plugin for jQuery by Piotr Rochala Which is a great plugin for nice scrollbars on most browsers but I am stuck because I am using it for a chat box and whenever the user appends new text to the boxit does scroll using the .scrollTop() method however the plugin's scrollbar doesnt scroll with it and when the user wants to look though the chat history it will start scrolling from near the top. I have made a quick demo of my situation http://jsfiddle.net/DY9CT/2/ Does anyone know how to solve this problem?

Why does this javascript based printing cause Safari to refresh the page?

The page I am working on has a javascript function executed to print parts of the page. For some reason, printing in Safari, causes the window to somehow update. I say somehow, because it does not really refresh as in reload the page, but rather it starts the "rendering" of the page from start, i.e. scroll to top, flash animations start from 0, and so forth. The effect is reproduced by this fiddle: http://jsfiddle.net/fYmnB/ Clicking the print button and finishing or cancelling a print in Safari causes the screen to "go white" for a sec, which in my real website manifests itself as something "like" a reload. While running print button with, let's say, Firefox, just opens and closes the print dialogue without affecting the fiddle page in any way. Is there something with my way of calling the browsers print method that causes this, or how can it be explained - and preferably, avoided? P.S.: On my real site the same occurs with Chrome. In the ex