Introduction
In this tutorial, i will show you how to edit an excel file in C# by using the EPPlus library. If you don't have the EPPlus library installed already in your project, you can view how to download and install it on our website.
EPPLUS Usage
For the purpose of this tutorial, we will use the below excel sample data.
The following code illustrates how to edit the above excel file and replace all Central
occurences by ABCD
:
// 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 in the sheet
int rows = worksheet.Dimension.Rows; // 10
// loop through the worksheet rows
for (int i = 1; i <= rows; i++)
{
// replace occurences
if(worksheet.Cells[i, 2].Value.ToString() == "Central")
worksheet.Cells[i, 2].Value = "ABCD";
}
// save changes
package.Save();
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 replace
all Central
occurences by ABCD
. When the loop is finished, we call the Save method upon our package object
to save all the changes that we made into our worksheet.
The result is as follows:
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;