Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read an excel file in C# without using Microsoft.Office.Interop.Excel libraries

I have a .Net-Windows application in C#. I need to open an excel and process it. How can I do this without using Microsoft.Office.Interop.Excel libraries?

like image 423
ASD Avatar asked Feb 06 '12 04:02

ASD


People also ask

What is Excel in C?

The Excel C API is the ideal choice when you want to create high-performance worksheet functions by creating XLL add-ins. The C API provides you with the most direct access to worksheet data. XLLs provide Excel with the most direct access to the DLL resources.


1 Answers

I highly recommend CSharpJExcel for reading Excel 97-2003 files (xls) and ExcelPackage for reading Excel 2007/2010 files (Office Open XML format, xlsx).

They both work perfectly. They have absolutely no dependency on anything.

Sample using CSharpJExcel:

Workbook workbook = Workbook.getWorkbook(new System.IO.FileInfo(fileName)); var sheet = workbook.getSheet(0); ... var content = sheet.getCell(colIndex, rowIndex).getContents(); ... workbook.close(); 

Sample using ExcelPackage:

using (ExcelPackage xlPackage = new ExcelPackage(existingFile)) {   // get the first worksheet in the workbook   ExcelWorksheet worksheet = xlPackage.Workbook.Worksheets[1];   int iCol = 2;  // the column to read    // output the data in column 2   for (int iRow = 1; iRow < 6; iRow++)     Console.WriteLine("Cell({0},{1}).Value={2}", iRow, iCol,        worksheet.Cell(iRow, iCol).Value);    // output the formula in row 6   Console.WriteLine("Cell({0},{1}).Formula={2}", 6, iCol,      worksheet.Cell(6, iCol).Formula);  } // the using statement calls Dispose() which closes the package. 

EDIT:

There is another project, ExcelDataReader, that seems to have the ability to handle both formats. It is also easy like the other ones I've mentioned.

There are also other libraries:

  • NPOI: Port of the Apache POI library to .NET:
    Very powerfull, free, and open source. In addition to Excel (97-2010) it also supports Word and PowerPoint files.

  • ExcelLibrary:
    It only support Excel 97-2003 (xls) files.

  • EPPlus:
    An extension to ExcelPackage. Easier to use (I guess).

like image 168
Mohammad Dehghan Avatar answered Sep 29 '22 10:09

Mohammad Dehghan