81

My application needs to read data from an excel file. I am using .Net and c# for development. I cannot install MS office in the system. Because of that the my application fails to read excel file and throws an error while loading the dll for excel.

How can i access excel file in my application in a system where ms office is not installed?

shekhar
  • 1,372
  • 2
  • 16
  • 23
TutuGeorge
  • 1,972
  • 2
  • 22
  • 42
  • 2
    OleDB or save it as a CSV file (as Robert Harvey suggested below). – Tim Apr 03 '13 at 16:55
  • for OleDB,we need to have ms excel installed in the machine , right?? – TutuGeorge Apr 03 '13 at 17:13
  • Can the convertion of excel to csv through code be done even if we dont have ms excel installed ??? – TutuGeorge Apr 03 '13 at 17:17
  • 1
    No you don't need Excel installed to use OleDb. However if your Excel file is an xlsx kind of file you need the more recent Microsoft Data Access component freely available for download – Steve Apr 03 '13 at 17:18
  • Why isn't anyone referencing any of the libraries mentioned in the following link? https://nugetmusthaves.com/Tag/Excel – Fractal Jul 29 '19 at 14:18
  • https://stackoverflow.com/questions/12996234/optimal-way-to-read-an-excel-file-xls-xlsx – Andrew Dec 03 '19 at 15:31

5 Answers5

108

There is the option to use OleDB and use the Excel sheets like datatables in a database...

Just an example.....

string con =
  @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\temp\test.xls;" + 
  @"Extended Properties='Excel 8.0;HDR=Yes;'";    
using(OleDbConnection connection = new OleDbConnection(con))
{
    connection.Open();
    OleDbCommand command = new OleDbCommand("select * from [Sheet1$]", connection); 
    using(OleDbDataReader dr = command.ExecuteReader())
    {
         while(dr.Read())
         {
             var row1Col0 = dr[0];
             Console.WriteLine(row1Col0);
         }
    }
}

This example use the Microsoft.Jet.OleDb.4.0 provider to open and read the Excel file. However, if the file is of type xlsx (from Excel 2007 and later), then you need to download the Microsoft Access Database Engine components and install it on the target machine.

The provider is called Microsoft.ACE.OLEDB.12.0;. Pay attention to the fact that there are two versions of this component, one for 32bit and one for 64bit. Choose the appropriate one for the bitness of your application and what Office version is installed (if any). There are a lot of quirks to have that driver correctly working for your application. See this question for example.

Of course you don't need Office installed on the target machine.

While this approach has some merits, I think you should pay particular attention to the link signaled by a comment in your question Reading excel files from C#. There are some problems regarding the correct interpretation of the data types and when the length of data, present in a single excel cell, is longer than 255 characters

Community
  • 1
  • 1
Steve
  • 213,761
  • 22
  • 232
  • 286
  • 3
    I get an exception with the code. What is Sheet1$ ? – Bengi Besçeli Feb 01 '15 at 16:03
  • 5
    It is the name of a worksheet in your excel file. Each sheet is considered as a different table with the name of the sheet and with a $ suffix. Of course, if you change the sheet name you need to change the tablename (sheet1$) used above – Steve Feb 01 '15 at 16:18
  • 3
    My Excel file contains a merged cell having multiline text. This approach reads only part of the text i.e. upto middle of the 7th line. Could you please help me? – bjan Mar 25 '16 at 06:09
  • 5
    Post a new question please, in this way you will get a lot more attention to you specific problem, than asking here on a 3 years old question/answer. And remember the 255 chars limit.... – Steve Mar 25 '16 at 08:12
  • 1
    @Steve it's possible using a sheet index in query select * from [0] ??? – daniele3004 Jun 09 '16 at 08:48
  • I doubt it. Following a FROM there must be a string with the name of the table. Changing this convention to introduce an index of an array seems to be rather inconsistent. However you can try to get the array of sheet (tables) using the GetSchema method of connection and then index that array – Steve Jun 09 '16 at 09:00
  • If you're __facing problem to read cells which contain numbers__ then connection string need to be modified as suggested in this post - [OleDbDataReader How to read number types?](https://stackoverflow.com/q/36723035/465053) – RBT Feb 15 '19 at 06:32
  • 1
    Why isn't anyone mentioning any of the libraries mentioned in this link? https://nugetmusthaves.com/Tag/Excel – Fractal Jul 29 '19 at 14:17
  • Perhaps because this is a 6 years old answer. Things change, and in any case using Jet OleDb 4.0 doesn't require any other library to distribute, just the framework – Steve Jul 29 '19 at 14:44
  • for Excel 2007 and above, please use below conection string else you will get multiple misguiding errors. conn = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties='Excel 12.0;HDR=NO';"; – Mohan Mar 11 '21 at 23:47
26

CSharpJExcel for reading Excel 97-2003 files (XLS), ExcelPackage for reading Excel 2007/2010 files (Office Open XML format, XLSX), and ExcelDataReader that seems to have the ability to handle both formats

Good luck!

Osama Rizwan
  • 615
  • 1
  • 7
  • 19
Obama
  • 2,586
  • 2
  • 30
  • 49
  • 4
    ExcelDataReader appears to be the most recently maintained. It's also available via NuGet. I've had much luck with it. – Michael Silver Jul 28 '14 at 00:29
  • 4
    For any future users, give a try to ExcelDataReader. It is a very good option especially if you build your application with Platform Target 'AnyCpu'. Otherwise the pain of installing x86 or x64 on client machines is a big pain. – Manvinder Sep 16 '14 at 06:47
  • Sorry to hijack this thread...How to import this excelreader folder in my projecct?? I am new to c# ..please help – nick Apr 29 '16 at 10:46
  • 1
    JExcelApi seems to be abandoned and I'm unable to find the version for C# (I found only Java). Also, Chrome is showing security warning for that ExcelPackage link. Anyway, here is [fast and efficient Excel reader](https://www.gemboxsoftware.com/spreadsheet/examples/c-sharp-open-read-excel-file/401) that I ended up using, you can find it on [NuGet](https://www.nuget.org/packages/GemBox.Spreadsheet). – Hazel Patton Dec 27 '19 at 06:45
  • For a 2020 solution can I shamelessly plug [ExcelToEnumerable](https://github.com/ChrisHodges/ExcelToEnumerable/). We've [benchmarked it](https://github.com/ChrisHodges/ExcelToEnumerable/wiki/Performance) and it's the fastest solution if you only need to support .xlsx files. *Disclaimer* I'm the author of ExcelToEnumerable. – Chris HG Feb 02 '20 at 19:52
9

Save the Excel file to CSV, and read the resulting file with C# using a CSV reader library like FileHelpers.

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
  • 1
    [TextFieldParser Class](http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.fileio.textfieldparser.aspx) in Microsoft.VisualBasic.FileIO assembly is included with .NET and is very good with CSV files, IMO. – Tim Apr 03 '13 at 16:57
  • 1
    Saving to CSV will result in the file having formatted values, rather than the underlying values (for example, rounded to two decimal places when the full precision is 6). This could be a problem depending on your data needs. – atheaos Sep 04 '15 at 14:55
9

I don't have a machine available to test this but it should work. First you will probably need to install the either the 2007 Office System Driver: Data Connectivity Components or the Microsoft Access Database Engine 2010 Redistributable. Then try the following code, note you will need to change the name of the Sheet in the Select statement below to match sheetname in your excel file:

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

namespace Data_Migration_Process_Creator
{
    class Class1
    {
        private DataTable GetDataTable(string sql, string connectionString)
        {
            DataTable dt = null;

            using (OleDbConnection conn = new OleDbConnection(connectionString))
            {
                conn.Open();
                using (OleDbCommand cmd = new OleDbCommand(sql, conn))
                {
                    using (OleDbDataReader rdr = cmd.ExecuteReader())
                    {
                        dt.Load(rdr);
                        return dt;
                    }
                }
            }
        }

        private void GetExcel()
        {
            string fullPathToExcel = "<Path to Excel file>"; //ie C:\Temp\YourExcel.xls
            string connString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0;HDR=yes'", fullPathToExcel);
            DataTable dt = GetDataTable("SELECT * from [SheetName$]", connString);

            foreach (DataRow dr in dt.Rows)
            {
                //Do what you need to do with your data here
            }
        }
    }
}

Note: I don't have an environment to test this in (One with Office installed) so I can't say if it will work in your environment or not but I don't see why it shouldn't work.

Mark Kram
  • 5,672
  • 7
  • 51
  • 70
5

Convert the excel file to .csv file (comma separated value file) and now you can easily be able to read it.

fat
  • 6,435
  • 5
  • 44
  • 70
petko_stankoski
  • 10,459
  • 41
  • 127
  • 231