How to Read an Excel File in C Sharp
Photo by Markus Spiske
Originally Posted On: https://ironsoftware.com/csharp/excel/tutorials/how-to-read-excel-file-csharp/
- Install IronXL Excel Library from NuGet or the DLL download
- Use the WorkBook.Load method to read any XLS, XLSX or CSV document.
- Get Cell values using intuitive syntax: sheet[“A11”].DecimalValue
In this tutorial, we will see how easy it is to read Excel files in C# or VB.Net using the IronXL “Excel” library.
Installation
The first thing we need to do is install the IronXL.Excel library, adding Excel functionality to the .NET framework.
We can do this using our NuGet package or by downloading the .Net Excel DLL.
PM > Install-Package IronXL.Excel
Read an XLS or XLSX File
In this example we can see that Excel files can be read efficiently without Interop in C#:
- using IronXL;
- using System.Linq;
- //Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSV
- WorkBook workbook = WorkBook.Load(“test.xlsx”);
- WorkSheet sheet = workbook.WorkSheets.First();
- //Select cells easily in Excel notation and return the calculated value
- int cellValue = sheet[“A2”].IntValue;
- // Read from Ranges of cells elegantly.
- foreach (var cell in sheet[“A2:A10”])
- {
- Console.WriteLine(“Cell {0} has value ‘{1}’”, cell.AddressString, cell.Text);
- }
- ///Advanced Operations
- //Calculate aggregate values such as Min, Max and Sum
- decimal sum = sheet[“A2:A10”].Sum();
- //Linq compatible
- decimal max = sheet[“A2:A10”].Max(c => c.DecimalValue);
Copy code to clipboardVB C#
The final Advanced Operations show Linq compatibility and aggregate range mathematics.
Learning More
Further Documentation
You may also find the IronXL class documentation within the Object Reference of great value.
In addition, there are other tutorials which may shed light in other aspects of IronXL.Excel including Creating, Reading, Editing Saving and Exporting XLS, XLSX and CSV files without using Excel Interop..