Read and Create/Write Excel files in .NET Core (2022)

Read and Create/Write Excel files in .NET Core (1)

Today in this article, we shall see how to perform Read and Create/Write Excel files in .NET Core-based application.

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
  • Read the content of the excel file using OpenXML API
  • Read Excel as JSON
  • Read Excel with Empty cell values
  • Export/Create/Write data to Excel using OpenXML
    • Summary

You don’t need Microsoft Office

Please note that Read, Create Excel(.xls, .xlsx) in C# is possible without installing Microsoft Office. Yes, you don’t really 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,

  • Read/Write Excel file in .NET Core using EPPlus
  • Read/Write Excel file in .NET Core using NPOI

Getting Started

Let’s create a .NET Core project, you can choose any project template, this SDK works perfectly for all projects. Here to keep it simple I am using a Console .NET Core 3.1 C# application.

(Below logic works perfectly fine for older .NET Core 2.x or any new .NET 5 or 6 version)

Read and Create/Write Excel files in .NET Core (2)

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 from Nuget package manager,

Read and Create/Write Excel files in .NET Core (3)

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 and Create/Write Excel files in .NET Core (4)

Read the content of the excel file 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 method as below,
using (SpreadsheetDocument doc = SpreadsheetDocument.Open(strDoc, false))

I am showing the results on a console,

Read and Create/Write Excel files in .NET Core (5)

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 as JSON

If you are interested to convert Excel as JSON it’s easy too. Please see here to know more about the same.

  • Read Excel as JSON using OpenXML SDK

Read Excel with Empty cell values

If you are interested to export Excel in C# with empty cell values, please see here one approach to reading excel data appropriately.

  • Read Excel with Empty cell values using OpenXML SDK


Export/Create/Write data to Excel using OpenXML

Let’s try now try to create or write the data to an Excel file.

Here is the sample data/object which we want to save as an Excel file.

Read and Create/Write Excel files in .NET Core (6)
Read and Create/Write Excel files in .NET Core (7)

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 Rows details as below,

Read and Create/Write Excel files in .NET Core (8)

That’s all, we just learned how to import and export data to/from excel in a simple way in .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.

  • Read/Write Excel file in .NET Core using EPPlus
  • Read/Write Excel file in .NET Core using NPOI

If interested to know on how to download excel(.xlsx) file, please see the below article,

  • Return or Download File in ASP.NET Core WebAPI

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 really 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 get a notification on freshly published best practices and guidelines for software design and development.

Related Posts:

  • Read files Google Cloud Storage using Python
  • EPPlus - Read/Write Excel file in .NET Core using
  • How to Add Chart to Excel File

You might also like

Latest Posts

Article information

Author: Rev. Leonie Wyman

Last Updated: 05/19/2022

Views: 5686

Rating: 4.9 / 5 (79 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Rev. Leonie Wyman

Birthday: 1993-07-01

Address: Suite 763 6272 Lang Bypass, New Xochitlport, VT 72704-3308

Phone: +22014484519944

Job: Banking Officer

Hobby: Sailing, Gaming, Basketball, Calligraphy, Mycology, Astronomy, Juggling

Introduction: My name is Rev. Leonie Wyman, I am a colorful, tasty, splendid, fair, witty, gorgeous, splendid person who loves writing and wants to share my knowledge and understanding with you.