Read an excel file in c#

Introduction


In this tutorial, i will show you how to read an excel file in C# by using the EPPlus library.

EPPLUS Download and Installation


EPPlus is a .NET library that allows you to read from and write to excel files. To download this library:

1- Go to Tools > NuGet Package Manager > Manage NuGet Packages for Solution...

NuGet Package Manager

2- Search for EPPlus.

3- Choose the first search result, check your project and click the install button.

Install EPPlus

4- Click the ok button.

Install EPPlus

EPPLUS Usage


For the purpose of this tutorial, we will use the below excel sample data.

Excel sample data

The following code illustrates how to read the above excel file.

// path to your excel file
string path = "C:/****/sample_data.xlsx";
FileInfo fileInfo = new FileInfo(path);

ExcelPackage package = new ExcelPackage(fileInfo);
ExcelWorksheet worksheet =  package.Workbook.Worksheets.FirstOrDefault();

// get number of rows and columns in the sheet
int rows = worksheet.Dimension.Rows; // 20
int columns = worksheet.Dimension.Columns; // 7

// loop through the worksheet rows and columns
for (int i = 1; i <= rows; i++) {
    for (int j = 1; j <= columns; j++) {

        string content = worksheet.Cells[i, j].Value.ToString();
        /* Do something ...*/
    }
}

In preceding code, we create a new instance of the ExcelPackage by passing the FileInfo object as a parameter of its constructor , wich enables us to access our excel file. package.Workbook.Worksheets provides access to multiple worksheets. Since our excel file contains only one worksheet, we use the FirstOrDefault method to access it. After that we loop through our worksheet and we get the value of each column of each row.


Note: by using the Dimension object, you need to be sure that the excel file you're working with is not empty. Otherwise, it will return null.

Namespace


To use EPPlus in your code, you have to include this namespace:

using OfficeOpenXml;

See also