Read and Write Excel Files in C# .NET Core
Today in this article, we shall see how to Read Excel files in C# .NET-based application and we will also see examples for write operations.
You must be wondering if there is an easy way to work on Excel in the .NET Core framework.
Here I am going to talk about a very simple approach of using OpenXML SDK from Microsoft (which is free and open-source).
The OpenXML SDK provides API for working with Office Word, Excel, and PowerPoint documents.
This SDK can be installed from NuGet as a package.
Today, in this article we shall cover below,
You don’t need Microsoft Office
Please note that Reading, and Creating Excel (.xls, .xlsx) in C# is possible without installing Microsoft Office.
Yes, you don’t need Microsoft Office to be installed on the machine.
Today we will see a few possible and easy-to-implement approaches.
If you are interested in a few more approaches like using EPPlus or NPOI library, kindly visit the below post for more details,
Getting Started
Let’s create a .NET Core project, you can choose any project template, and this SDK works perfectly for all projects. Here to keep it simple I am using a Console .NET Core 3.1 C# application.
(The below logic works perfectly fine for older .NET Core or any new .NET 6 version)
The NuGet package name is DocumentFormat.OpenXml. Let’s install this package,
PM> Install-Package Open-XML-SDK -Version 2.9.0
Note: Please use the latest available version.
OR
Please install it from the NuGet package manager,
Once you install this NuGet package, you get full library support on Reading, Writing Excel (.xlsx), Word (.doc), or Powerpoint(.ppt) files using C# API.
Let’s look at an example, I have a simple Excel file with the below column and row details. Let’s try to read the file using our API,
Read Excel files in C# .NET using OpenXML API
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.
Sample methods are as below,
static void ReadExcelFile()
{
try
{
//Lets open the existing excel file and read through its content . Open the excel using openxml sdk
using (SpreadsheetDocument doc = SpreadsheetDocument.Open("testdata.xlsx", false))
{
//create the object for workbook part
WorkbookPart workbookPart = doc.WorkbookPart;
Sheets thesheetcollection = workbookPart.Workbook.GetFirstChild<Sheets>();
StringBuilder excelResult = new StringBuilder();
//using for each loop to get the sheet from the sheetcollection
foreach (Sheet thesheet in thesheetcollection)
{
excelResult.AppendLine("Excel Sheet Name : " + thesheet.Name);
excelResult.AppendLine("----------------------------------------------- ");
//statement to get the worksheet object by using the sheet id
Worksheet theWorksheet = ((WorksheetPart)workbookPart.GetPartById(thesheet.Id)).Worksheet;
SheetData thesheetdata = (SheetData)theWorksheet.GetFirstChild<SheetData>();
foreach (Row thecurrentrow in thesheetdata)
{
foreach (Cell thecurrentcell in thecurrentrow)
{
//statement to take the integer value
string currentcellvalue = string.Empty;
if (thecurrentcell.DataType != null)
{
if (thecurrentcell.DataType == CellValues.SharedString)
{
int id;
if (Int32.TryParse(thecurrentcell.InnerText, out id))
{
SharedStringItem item = workbookPart.SharedStringTablePart.SharedStringTable.Elements<SharedStringItem>().ElementAt(id);
if (item.Text != null)
{
//code to take the string value
excelResult.Append(item.Text.Text + " ");
}
else if (item.InnerText != null)
{
currentcellvalue = item.InnerText;
}
else if (item.InnerXml != null)
{
currentcellvalue = item.InnerXml;
}
}
}
}
else
{
excelResult.Append(Convert.ToInt16(thecurrentcell.InnerText) + " ");
}
}
excelResult.AppendLine();
}
excelResult.Append("");
Console.WriteLine(excelResult.ToString());
Console.ReadLine();
}
}
}
catch (Exception)
{
}
}
After executing the above logic, 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
- Also if needed you can keep the file locally for ex.
string strDoc = @”C:\Users\Public\Documents\testdata.xlsx” then use the method as below,
using (SpreadsheetDocument doc = SpreadsheetDocument.Open(strDoc, false))
I am showing the results on a console,
One can map the above output details to respective C# class objects using the mapping logic of their choice.
This way data can be transferred for further processing within the application if needed. For example for write operations, I have used a similar C# class UserDetails.
Read Excel files in C# .NET as JSON
If you are interested in converting Excel as JSON it’s easy too. Please see here to know more about the same.
Read Excel with Empty cell values
If you are interested in exporting Excel in C# with empty cell values, please see here one approach to reading Excel data appropriately.
Export/Create/Write Excel files in C# .NET using OpenXML
Let’s try now to create or write the data in an Excel file.
Here is the sample data/object which we want to save as an Excel file.
Here we need to use the OpenXML Create () C# method as shown below,
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 logic can be found below,
static void WriteExcelFile()
{
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)));
using (SpreadsheetDocument document = SpreadsheetDocument.Create("TestNewData.xlsx", SpreadsheetDocumentType.Workbook))
{
WorkbookPart workbookPart = document.AddWorkbookPart();
workbookPart.Workbook = new Workbook();
WorksheetPart worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
var sheetData = new SheetData();
worksheetPart.Worksheet = new Worksheet(sheetData);
Sheets sheets = workbookPart.Workbook.AppendChild(new Sheets());
Sheet sheet = new Sheet() { Id = workbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "Sheet1" };
sheets.Append(sheet);
Row headerRow = new Row();
List<String> columns = new List<string>();
foreach (System.Data.DataColumn column in table.Columns)
{
columns.Add(column.ColumnName);
Cell cell = new Cell();
cell.DataType = CellValues.String;
cell.CellValue = new CellValue(column.ColumnName);
headerRow.AppendChild(cell);
}
sheetData.AppendChild(headerRow);
foreach (DataRow dsrow in table.Rows)
{
Row newRow = new Row();
foreach (String col in columns)
{
Cell cell = new Cell();
cell.DataType = CellValues.String;
cell.CellValue = new CellValue(dsrow[col].ToString());
newRow.AppendChild(cell);
}
sheetData.AppendChild(newRow);
}
workbookPart.Workbook.Save();
}
}
Once you execute this API ‘workbookPart.Workbook.Save()’ will save the file to the ‘bin’ folder location. You can modify the location of the generated file if 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.
Please visit the GitHub link for the complete code.
Other References :
EPPlus and EPOI for Reading and Writing of Excel file, kindly visit the below post for more details.
If interested to know on how to download Excel (.xlsx) files, please see the below article,
Please use the below Tutorial to use the above code and quickly get started,
This was very much basic while dealing with Excel in .NET Core which we covered today in this article.
Hope this helps you get started.
Are you dealing with any complex scenarios? Please let me know and sound off your comments below!
Summary
The Open XML SDK provides us full control to deal with Office Word, Excel, and PowerPoint documents. As this SDK is free and open-source from Microsoft, we don’t need to use any other third-party tools/libraries. This SDK works best!
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.
Inaccessible due to its protection level
Hello John – Could you elaborate on your question please.
What is the namespace of SpreadsheetDocument ?
Hey Satish , you will need to add below namespace
“using DocumentFormat.OpenXml.Spreadsheet”
Also additionally you may need
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
Thanks .. Helped me setup the code great way!
Thank you Martin! Glad the content helped you!
How do i format excel using above code? i mean how to add bold, number format or autosize the columns.
I need to map a model instead of using just the string
Hi Evan- You can very much do that. Please check “write excel” file part of the article, as I have used the model for the same.
I need to read a csv file that create an xlsx file with with data and graphs. Will Open XML SDK allow me to do this?
Hey David- To read CSV file , you can use other tools like explained here Read CSV files in .NET Core. Once you parse input CSV as JSON or other format , you can use OpenXML SDK for the conversion and graphs.
i need to work with dataset which contains multiple datatables and each data table should be saved into individual sheeets in single excell file.
Hi Jhansi- Thanks for your query. Please use the above Write logic for the same and extend it. It should perfectly work for your requirements. Here you should iterate over all tables from the given dataset by keeping excel handle open and each table can be written each sheet.
I need to pick particular coloumn how do i do it?
Please help
Hey Deepak- Thanks for your query! You need to iterate over the columns and set your criteria based on column name and value (if relevant) for columns you are looking for .Hope this helps!
Thank you!
Thanks Murphycn for the feedback!
Thanks for your post, it is really helpful!
Is there a way to set the width of a cell when i append it to the row? My header data is quite wide.
Hello Lilly. Glad you liked the article.
You can use Cell ‘Column’ properties to define the required width of your header. Hope this helps.
Nicely explained. Thanks.