Working with Excel in C# (.NET): Overview of Popular Libraries
In modern .NET platform development, there is often a need for programmatic interaction with Microsoft Excel files. This can include report generation, data import, table export, or document workflow automation. In this article, we will look at three of the most popular libraries for working with Excel in C#: EPPlus, ClosedXML, and NPOI. Each of them has its own features, advantages, and limitations.
1. EPPlus — A Powerful Tool for Working with XLSX
EPPlus is one of the most popular libraries for working with the Office Open XML (XLSX) format. It provides an extensive API for creating, reading, and formatting Excel documents. Starting from version 5, EPPlus is distributed under the Polyform Noncommercial license (free only for non-commercial use); however, a license purchase is required for commercial projects.
Key Features:
- Full support for cell formatting (fonts, colors, borders, alignment)
- Working with charts, pivot tables, and conditional formatting
- Support for formulas and calculations
- Working with images and comments
- High performance when working with large files
Example of creating an Excel file using EPPlus:
using OfficeOpenXml;
class Program{ static void Main() { ExcelPackage.LicenseContext = LicenseContext.NonCommercial; // License required for commercial use using (var package = new ExcelPackage()) { var worksheet = package.Workbook.Worksheets.Add("Report"); // Fill headers worksheet.Cells["A1"].Value = "Name"; worksheet.Cells["B1"].Value = "Age"; worksheet.Cells["C1"].Value = "City"; // Fill data worksheet.Cells["A2"].Value = "Anna"; worksheet.Cells["B2"].Value = 28; worksheet.Cells["C2"].Value = "Moscow"; // Formatting worksheet.Cells["A1:C1"].Style.Font.Bold = true; worksheet.Cells["A1:C1"].Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid; worksheet.Cells["A1:C1"].Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.LightBlue); // Save file package.SaveAs(new FileInfo("report.xlsx")); } }}2. ClosedXML — Simple and Intuitive API
ClosedXML is an open-source library (MIT license) that provides a convenient and concise interface for working with XLSX files. It is built on top of DocumentFormat.OpenXml but hides the complexity of the low-level API. ClosedXML is ideal for quickly generating reports and simple tables.
Advantages of ClosedXML:
- Simple and readable syntax
- Completely free for commercial use
- Good support for styles and formatting
- Built-in support for working with dates and formulas
Example of reading data from Excel using ClosedXML:
using ClosedXML.Excel;
class Program{ static void Main() { using (var workbook = new XLWorkbook("data.xlsx")) { var worksheet = workbook.Worksheet(1); // Read data row by row foreach (var row in worksheet.RowsUsed()) { var name = row.Cell(1).GetValue<string>(); var age = row.Cell(2).GetValue<int>(); var city = row.Cell(3).GetValue<string>(); Console.WriteLine($"{name}, {ag