Working with Excel in C# (.NET): Best Libraries and Examples
Working with Excel spreadsheets is one of the most common tasks in corporate C# development. Whether it's generating reports, importing data, or automating routine operations, you need a reliable tool. In this article, we will cover three popular libraries for working with Excel in the .NET ecosystem: EPPlus, ClosedXML, and NPOI. You will learn their features, strengths, and see code examples.
1. EPPlus — Powerful and Modern Tool
EPPlus is one of the most popular libraries for working with Excel files (.xlsx) in .NET. It supports almost all Excel features: formatting, charts, pivot tables, conditional formatting, and much more. Starting from version 5, EPPlus is distributed under the Polyform Noncommercial license (free for non-commercial use); a license purchase is required for commercial use.
Installation
Install-Package EPPlusExample: Creating a Simple Excel File
using OfficeOpenXml;
class Program{ static void Main() { // Set license context (for non-commercial use) ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
using (var package = new ExcelPackage()) { var worksheet = package.Workbook.Worksheets.Add("Report"); // Headers worksheet.Cells["A1"].Value = "Name"; worksheet.Cells["B1"].Value = "Age"; worksheet.Cells["C1"].Value = "City"; // Data worksheet.Cells["A2"].Value = "Anna"; worksheet.Cells["B2"].Value = 28; worksheet.Cells["C2"].Value = "Moscow"; worksheet.Cells["A3"].Value = "Ivan"; worksheet.Cells["B3"].Value = 35; worksheet.Cells["C3"].Value = "Saint Petersburg"; // 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); // Auto-fit columns worksheet.Cells.AutoFitColumns();
// Save var file = new FileInfo("Report.xlsx"); package.SaveAs(file); } }}Pros of EPPlus:
- Support for complex objects: charts, pivot tables, sparklines
- High performance when working with large files
- Excellent documentation and active community
Cons: Paid commercial license, no support for .xls (old format).
2. ClosedXML — Simplicity and Convenience
ClosedXML is a free open-source library that provides a convenient API for working with Excel. It is built on top of the OpenXML SDK but hides all the complexity, offering an intuitive interface. It is ideal for quickly creating reports and tables.
Installation
Install-Package ClosedXMLExample: Creating a File with Formatting
using ClosedXML.Excel;
class Program{ static void Main() { using (var workbook = new XLWorkbook()) { var ws = workbook.Worksheets.Add("Sales"); // Headers ws.Cell("A1").Value = "Product"; ws.Cell("B1").Value = "Quantity"; ws.Cell("C1").Value = "Price"; // Data ws.Cell("A2").Value = "Laptop"; ws.Cell("B2").Value = 5; ws.Cell("C2").Value =