C# NPOI – How to Read and Write Excel files in .NET
Today in this article we shall see how to use NPOI to perform Read and Write Excel files in C#.NET Core.
In our last post, we saw the usage of OpenXML SDK (open-source SDK from Microsoft) to work with Office Word, Excel, and PowerPoint.
We also looked at another easy-to-use library called EPPlus too.
Today, in this article we shall cover below using NPOI,
Please see the below references if interested to know more about them.
We shall be looking into one more simple approach to dealing with Office Excel using the NPOI .NET Core Library.
You don’t need Microsoft Office
Please note that reading and Creating Excel in C# is possible without installing Microsoft Office. Today we will see a possible and easy-to-implement approach.
What is NPOI
NPOI is an open-source.NET framework library that offers a wide range of APIs for managing Excel documents, making it a great option for developers to automate operations involving spreadsheets.
Utilizing NPOI, you can efficiently manipulate data, add formatting, read existing Excel files, and add formulas.
It offers a dependable solution for Excel integration in C# applications and is actively maintained and free to use, saving time and resources for developers.
It supports several Excel file types, including.xls and.xlsx, providing versatility and compatibility with multiple Excel versions.
Getting Started
Let’s create a .NET Core project, you can choose any project template. Here we shall use the .NET Core 3.1 or .NET 6 Console project.
NuGet’s package name is NPOI.
Let’s install this package.
PM> Install-Package NPOI -Version <version>
OR
Please install from Nuget Package Manager,
Note: Please use the latest available version
Let’s look at a simple Excel file with the below column and row details. Let’s try to read the file using our NPOI API,
Read the content of the Excel file using C# NPOI
POC example as below. This ready to use API can be used in .NET Core console, or Test project or ASP.NET Core application or logic can be modified or improved as per your requirements.
static string ReadExcel()
{
DataTable dtTable = new DataTable();
List<string> rowList = new List<string>();
ISheet sheet;
using (var stream = new FileStream("TestData.xlsx", FileMode.Open))
{
stream.Position = 0;
XSSFWorkbook xssWorkbook = new XSSFWorkbook(stream);
sheet = xssWorkbook.GetSheetAt(0);
IRow headerRow = sheet.GetRow(0);
int cellCount = headerRow.LastCellNum;
for (int j = 0; j < cellCount; j++)
{
ICell cell = headerRow.GetCell(j);
if (cell == null || string.IsNullOrWhiteSpace(cell.ToString())) continue;
{
dtTable.Columns.Add(cell.ToString());
}
}
for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
{
IRow row = sheet.GetRow(i);
if (row == null) continue;
if (row.Cells.All(d => d.CellType == CellType.Blank)) continue;
for (int j = row.FirstCellNum; j < cellCount; j++)
{
if (row.GetCell(j) != null)
{
if (!string.IsNullOrEmpty(row.GetCell(j).ToString()) && !string.IsNullOrWhiteSpace(row.GetCell(j).ToString()))
{
rowList.Add(row.GetCell(j).ToString());
}
}
}
if(rowList.Count>0)
dtTable.Rows.Add(rowList.ToArray());
rowList.Clear();
}
}
return JsonConvert.SerializeObject(dtTable);
}
After executing the above API, one can easily read all the Excel details.
- In the above example, I have used the file “testdata.xlsx” as input. I have kept this file in the output directory bin\Debug\netcoreapp3.1.
- Also if needed you can keep the file locally like ex.
string strDoc = @”C:\Users\Public\Documents\testdata .xlsx” .
I am showing the results as JSON out as shown below,
One can map the above output details to respective class objects using the mapping logic of their choice.
Export/Write the data to an Excel file using NPOI
We shall now look at creating or writing the data into an Excel file.
Here is the sample data/object which we want to save as an Excel file.
I am creating a new Excel file in the same project folder to keep everything simple. (Excel file will get created in the ‘bin’ folder of the project). The complete sample API is as below.
static void WriteExcel()
{
List<UserDetails> persons = new List<UserDetails>()
{
new UserDetails() {ID="1001", Name="ABCD", City ="City1", Country="USA"},
new UserDetails() {ID="1002", Name="PQRS", City ="City2", Country="INDIA"},
new UserDetails() {ID="1003", Name="XYZZ", City ="City3", Country="CHINA"},
new UserDetails() {ID="1004", Name="LMNO", City ="City4", Country="UK"},
};
// Lets converts our object data to Datatable for a simplified logic.
// Datatable is most easy way to deal with complex datatypes for easy reading and formatting.
DataTable table = (DataTable)JsonConvert.DeserializeObject(JsonConvert.SerializeObject(persons), (typeof(DataTable)));
var memoryStream = new MemoryStream();
using (var fs = new FileStream("Result.xlsx", FileMode.Create, FileAccess.Write))
{
IWorkbook workbook = new XSSFWorkbook();
ISheet excelSheet = workbook.CreateSheet("Sheet1");
List<String> columns = new List<string>();
IRow row = excelSheet.CreateRow(0);
int columnIndex = 0;
foreach (System.Data.DataColumn column in table.Columns)
{
columns.Add(column.ColumnName);
row.CreateCell(columnIndex).SetCellValue(column.ColumnName);
columnIndex++;
}
int rowIndex = 1;
foreach (DataRow dsrow in table.Rows)
{
row = excelSheet.CreateRow(rowIndex);
int cellIndex = 0;
foreach (String col in columns)
{
row.CreateCell(cellIndex).SetCellValue(dsrow[col].ToString());
cellIndex++;
}
rowIndex++;
}
workbook.Write(fs);
}
}
Once you execute ‘workbook.Write(fs)‘ will save the file to the ‘bin’ folder location. You can modify the location of the generated file as needed.
After executing the above API, a new Excel file will be created with the above custom objects transformed into respective Excel Columns and row details as below,
That’s all, we just learned how to import and export data to/from Excel in a simple way in a .NET Core framework-based application using the NPOI library.
Please visit the GitHub link for the complete code.
Other References :
Are you dealing with any complex scenarios? Please let me know and sound off your comments below!
Summary
The NPOI library provides us with easy control while dealing with the Office Excel file. Today we learned, how to import and export data to/from Excel in the .NET Core framework using the NPOI library.
The legacy so-called applications like Excel or Word are no more legacy and can be used on any platform using simple libraries like NPOI etc.
Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.
Thank you for this excellent article. However, you should always add all essentials coding parts. Without the required ‘using’ clauses, one won’t get the classes definitions identified by the IDE.
Hey Rajesh- Thanks for the inputs! Glad it helped you! Sure will update the ‘using’ statements used in the article.
hi thanks for the exemples.
i have question : what is the best way to do to use a template xlsx file, fill it without saving the template, and save the work in a new xlsx file?
thanks for the help
Hi Khalid- Thanks for your query. You can use the read method above for reading the template and fill it in memory as table or dataset (if file size is not big ) later use in-memory data to save it as new excel.
Hello Sir .. I got a very big help from this article . Thumbs up.
Can you please a code snippet where i can format cell
Hello Naved, Thank you. glad it helped you. do you have any specific requirements for cell formatting, let me know I shall put some samples on it.
Do you know how I can get help on using NPOI from vba? I’ve downloaded and built NPOI.dll, but I don’t know how to call it and I can’t find any examples of vba usage. My purpose is to build an excel file from an Access runtime on a machine where office is not installed.
Hi- Thanks for your query. I have not tried NPOI using VBA yet. I shall post more on it if happen to get more details.
Does NPOI support cell formatting for example background color and table borders etc..
Hi Uttam, yes NPOI supports cell formatting!
Thanks for your examples. I just want to point out that this is a coding issue:
if (cell == null || string.IsNullOrWhiteSpace(cell.ToString())) continue;
{
dtTable.Columns.Add(cell.ToString());
}
Thanks, Meinrad. Glad it helped you. I shall fix the mentioned coding issue soon.
HI
should we read Excel macro ?
Hi Subodhan- Thanks for your query. I have not tried yet. Have you? I will let you know.
I have tried but not getting the correct result , If you know request to help
Need to copy Excel Macro in object using C# ?
Hello, I want to excel library with NPOI, EEPLUS, OpenXML..
can i free to use it?
i think that EEPLUS for a fee.
Hey John- Thanks for your query! As I am aware OpenXML is free and Open-sourced from Microsft. For EPPULUS and NPOI kindly check their licensing terms and conditions. Have a good day!
How would I do this for both .xls and .xlsx files? Would I just change it from XSSFWorkbook to just Workbook?
Hi Patrick- EPPLus support excel file with Excel 2007/2010 format i.e xlsx. If you would like to use .xls then you can try to use OpenXML SDK or NPOI library.
I hope this helps. Thanks.
Hello, this is an excellent article, can you please show us example how to export byte[] array image to excel?
Hello Mujtaba,
Thanks for the feedback.
Please see article to insert the image in EXCEL
How to Add Image to Excel Files using NPOI
Logic shown by you is very much generic , exactly what I wanted . Thank you..
Hello Baojam – Thank you ! appreciate your comments.