ZetCode

C# Excel

last modified November 6, 2026

In this article we show how to work with Excel files in C# with the ClosedXML library.

Excel file formats

We work with .xlsx files. The format is based on the Office Open XML standard: an .xlsx file is a ZIP archive of XML documents. Related formats include:

ClosedXML

ClosedXML is an open-source .NET library for reading, modifying, and writing Excel 2007+ files (.xlsx, .xlsm). It is built on the Open XML SDK and does not need Excel to be installed. The examples were tested with ClosedXML 0.105 on .NET 10.

$ dotnet add package ClosedXML

The examples write files to the current working directory, which is the project directory when the program is started with dotnet run.

Create an Excel file

In the first example, we create a new workbook and write values of different types into cells.

Program.cs
using ClosedXML.Excel;

using var wbook = new XLWorkbook();

var ws = wbook.Worksheets.Add("Sheet1");

ws.Cell("A1").Value = "falcon";
ws.Cell("A2").Value = 150;
ws.Cell("A3").Value = 3.14;
ws.Cell("A4").Value = new DateTime(2026, 11, 6);
ws.Cell("A5").Value = true;

ws.Column("A").AdjustToContents();

wbook.SaveAs("simple.xlsx");

Console.WriteLine($"Saved {ws.CellsUsed().Count()} cells to simple.xlsx");

A workbook is the Excel file; it contains one or more worksheets.

using var wbook = new XLWorkbook();

var ws = wbook.Worksheets.Add("Sheet1");

We create an empty XLWorkbook and add a worksheet named Sheet1. A workbook must have at least one worksheet to be saved.

ws.Cell("A1").Value = "falcon";
ws.Cell("A2").Value = 150;

The Value property is an XLCellValue, which converts implicitly from strings, numbers, dates, and booleans. The type of the C# value determines the type of the cell; the number 150 is stored as a number, not as text.

wbook.SaveAs("simple.xlsx");

The SaveAs method writes the workbook to a file.

$ dotnet run
Saved 5 cells to simple.xlsx

Read an Excel file

In the next example, we read the file created in the previous example.

Program.cs
using ClosedXML.Excel;

using var wbook = new XLWorkbook("simple.xlsx");

var ws = wbook.Worksheet(1);
Console.WriteLine($"Sheet: {ws.Name}, used range: {ws.RangeUsed()?.RangeAddress}");

foreach (var cell in ws.CellsUsed())
{
    Console.WriteLine($"{cell.Address}: {cell.Value} ({cell.DataType})");
}

string word = ws.Cell("A1").GetValue<string>();
int n = ws.Cell("A2").GetValue<int>();
DateTime date = ws.Cell("A4").GetDateTime();

Console.WriteLine($"{word} {n + 1} {date:yyyy-MM-dd}");

Passing a file name to the constructor opens an existing workbook.

var ws = wbook.Worksheet(1);

Worksheets can be accessed by their position, starting from 1, or by name.

foreach (var cell in ws.CellsUsed())
{
    Console.WriteLine($"{cell.Address}: {cell.Value} ({cell.DataType})");
}

CellsUsed returns the cells that are not empty. The DataType property shows the type of each value. Excel has no separate date type; a date is a number with a date format, which ClosedXML reports as DateTime.

string word = ws.Cell("A1").GetValue<string>();
int n = ws.Cell("A2").GetValue<int>();
DateTime date = ws.Cell("A4").GetDateTime();

GetValue<T> converts a cell value to a C# type, and methods such as GetString and GetDateTime return values of a specific type.

$ dotnet run
Sheet: Sheet1, used range: A1:A5
A1: falcon (Text)
A2: 150 (Number)
A3: 3.14 (Number)
A4: 11/6/2026 12:00:00 AM (DateTime)
A5: TRUE (Boolean)
falcon 151 2026-11-06

Cells

A cell is the intersection of a row and a column. Its address consists of the column letter and the row number; the upper-left cell is A1.

Program.cs
using ClosedXML.Excel;

using var wbook = new XLWorkbook();

var ws = wbook.AddWorksheet("Sheet1");

ws.FirstCell().Value = 150;
ws.Cell(3, 2).Value = "Hello there!";
ws.Cell("A6").SetValue("falcon").SetActive();

ws.Column(2).AdjustToContents();

Console.WriteLine($"First cell: {ws.FirstCell().Address}");
Console.WriteLine($"Cell(3, 2): {ws.Cell(3, 2).Address} = {ws.Cell(3, 2).Value}");
Console.WriteLine($"Active cell: {ws.ActiveCell?.Address}");
Console.WriteLine($"Empty cell: {ws.Cell("D4").IsEmpty()}");

wbook.SaveAs("cells.xlsx");

The example shows several ways to reference a cell.

ws.FirstCell().Value = 150;

FirstCell returns the first cell of the sheet, A1.

ws.Cell(3, 2).Value = "Hello there!";

A cell can be referenced by its row and column numbers. Row 3 and column 2 is cell B3.

ws.Cell("A6").SetValue("falcon").SetActive();

The SetValue method returns the cell, so calls can be chained. SetActive makes the cell selected when the file is opened.

ws.Column(2).AdjustToContents();

We adjust the width of the second column so that the text is fully visible.

$ dotnet run
First cell: A1
Cell(3, 2): B3 = Hello there!
Active cell: A6
Empty cell: True

Styles

The Style property of a cell, range, row, or column controls fonts, alignment, borders, fills, and number formats.

Program.cs
using ClosedXML.Excel;

using var wbook = new XLWorkbook();

var ws = wbook.Worksheets.Add("Sheet1");

ws.Column("A").Width = 25;
ws.Column("B").Width = 15;
ws.Row(3).Height = 30;

ws.Cell("A3").Value = "an old falcon";
ws.Cell("B2").Value = 150;
ws.Cell("B5").Value = "Sunny day";
ws.Cell("A7").Value = "Total";
ws.Cell("B7").Value = 1234.5;

var a3 = ws.Cell("A3").Style;
a3.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
a3.Alignment.Vertical = XLAlignmentVerticalValues.Center;
a3.Font.Italic = true;

ws.Cell("B2").Style.Border.OutsideBorder = XLBorderStyleValues.Thin;
ws.Cell("B5").Style.Font.FontColor = XLColor.Red;

ws.Range("A7:B7").Style
    .Font.SetBold()
    .Fill.SetBackgroundColor(XLColor.LightGray);
ws.Cell("B7").Style.NumberFormat.Format = "#,##0.00";

wbook.SaveAs("styled.xlsx");

Console.WriteLine($"B7 shown as: {ws.Cell("B7").GetFormattedString()}");

We set the widths of columns A and B and the height of row 3.

var a3 = ws.Cell("A3").Style;
a3.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
a3.Alignment.Vertical = XLAlignmentVerticalValues.Center;
a3.Font.Italic = true;

The text in A3 is centered horizontally and vertically and set in italics.

ws.Cell("B2").Style.Border.OutsideBorder = XLBorderStyleValues.Thin;
ws.Cell("B5").Style.Font.FontColor = XLColor.Red;

Cell B2 gets a thin border, and the text in B5 is red.

ws.Range("A7:B7").Style
    .Font.SetBold()
    .Fill.SetBackgroundColor(XLColor.LightGray);

The Set methods return the style, so several properties can be set in a chain. The style is applied to all cells of the range.

ws.Cell("B7").Style.NumberFormat.Format = "#,##0.00";

A number format changes how a number is displayed, not the stored value. GetFormattedString returns the displayed text.

Styled cells
Figure: Styled cells (rendered with LibreOffice)
$ dotnet run
B7 shown as: 1,234.50

Ranges and merged cells

A range is a rectangular group of cells. Its address consists of the upper-left and the lower-right cells separated by a colon, for example B10:D12.

Program.cs
using ClosedXML.Excel;

using var wbook = new XLWorkbook();

var ws = wbook.Worksheets.Add("Sheet1");

ws.Range("D2:E2").Style.Fill.BackgroundColor = XLColor.LightGray;
ws.Ranges("C5, F5:G8").Style.Fill.BackgroundColor = XLColor.LightBlue;

var range = ws.Range("B10:D12");
int i = 1;

foreach (var cell in range.Cells())
{
    cell.Value = i * 10;
    i++;
}

range.Style.Border.OutsideBorder = XLBorderStyleValues.Medium;
range.Style.Border.InsideBorder = XLBorderStyleValues.Thin;

Console.WriteLine($"Range {range.RangeAddress}: {range.RowCount()} rows, {range.ColumnCount()} columns");
Console.WriteLine($"Values: {string.Join(" ", range.Cells().Select(c => c.Value))}");

ws.Cell("B1").Value = "Merged title";
var title = ws.Range("B1:E1").Merge();
title.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
title.Style.Font.Bold = true;

Console.WriteLine($"Merged: {ws.Cell("C1").IsMerged()}, ranges: {ws.MergedRanges.Count}");

wbook.SaveAs("ranges.xlsx");

Range creates a single range; Ranges takes a comma-separated list of addresses.

foreach (var cell in range.Cells())
{
    cell.Value = i * 10;
    i++;
}

Cells returns the cells of the range row by row. We fill the nine cells with multiples of ten.

range.Style.Border.OutsideBorder = XLBorderStyleValues.Medium;
range.Style.Border.InsideBorder = XLBorderStyleValues.Thin;

The range gets a medium outside border and thin inside borders.

var title = ws.Range("B1:E1").Merge();

Merge joins the cells of a range into one cell. The value of the merged cell is the value of its first cell, B1. IsMerged returns true for any cell inside a merged range.

Ranges and a merged cell
Figure: Ranges and a merged cell (rendered with LibreOffice)
$ dotnet run
Range B10:D12: 3 rows, 3 columns
Values: 10 20 30 40 50 60 70 80 90
Merged: True, ranges: 1

Formulas

The FormulaA1 property sets a formula with A1-style references. ClosedXML has its own calculation engine, so formula results are available without Excel.

Program.cs
using ClosedXML.Excel;

using var wbook = new XLWorkbook();

var ws = wbook.Worksheets.Add("Sales");

ws.Cell("A1").Value = "Month";
ws.Cell("B1").Value = "Sales";

string[] months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"];
int[] sales = [1200, 950, 1430, 1100, 1675, 1320];

for (int i = 0; i < months.Length; i++)
{
    ws.Cell(i + 2, 1).Value = months[i];
    ws.Cell(i + 2, 2).Value = sales[i];
}

ws.Cell("A8").Value = "Total";
ws.Cell("B8").FormulaA1 = "SUM(B2:B7)";
ws.Cell("A9").Value = "Average";
ws.Cell("B9").FormulaA1 = "AVERAGE(B2:B7)";
ws.Range("A8:B9").Style.Font.Bold = true;
ws.Cell("B9").Style.NumberFormat.Format = "0.00";

Console.WriteLine($"B8 formula: {ws.Cell("B8").FormulaA1}, value: {ws.Cell("B8").Value}");
Console.WriteLine($"B9 formula: {ws.Cell("B9").FormulaA1}, value: {ws.Cell("B9").Value}");
Console.WriteLine($"B9 shown as: {ws.Cell("B9").GetFormattedString()}");
Console.WriteLine($"Max: {ws.Evaluate("MAX(B2:B7)")}");
Console.WriteLine($"Months over 1200: {ws.Evaluate("COUNTIF(B2:B7, \">1200\")")}");

wbook.SaveAs("formulas.xlsx");

We write the sales for six months into columns A and B.

ws.Cell("B8").FormulaA1 = "SUM(B2:B7)";

The formula is written without the leading equals sign. Reading Value of the cell calculates the formula.

Console.WriteLine($"Max: {ws.Evaluate("MAX(B2:B7)")}");

Evaluate calculates an expression in the context of the worksheet without writing it into a cell.

Formulas
Figure: Formulas (rendered with LibreOffice)
$ dotnet run
B8 formula: SUM(B2:B7), value: 7675
B9 formula: AVERAGE(B2:B7), value: 1279.1666666666667
B9 shown as: 1279.17
Max: 1675
Months over 1200: 3

Tables

An Excel table is a named range with a header row, filter buttons, and a style. InsertTable creates a table from a collection of objects.

Program.cs
using ClosedXML.Excel;

List<Product> products =
[
    new("Laptop", "Electronics", 899.99m, 12),
    new("Desk", "Furniture", 249.5m, 4),
    new("Mouse", "Electronics", 19.9m, 85),
    new("Chair", "Furniture", 129m, 9),
    new("Monitor", "Electronics", 219m, 21),
];

using var wbook = new XLWorkbook();
var ws = wbook.Worksheets.Add("Products");

IXLTable table = ws.Cell("A1").InsertTable(products, "ProductTable", true);

table.Theme = XLTableTheme.TableStyleMedium2;

ws.Column("C").Style.NumberFormat.Format = "#,##0.00";
ws.Columns().AdjustToContents();
ws.SheetView.FreezeRows(1);

Console.WriteLine($"Table {table.Name} at {table.RangeAddress}");
Console.WriteLine($"Columns: {string.Join(", ", table.Fields.Select(f => f.Name))}");
Console.WriteLine($"Data rows: {table.DataRange.RowCount()}");

wbook.SaveAs("products.xlsx");

record Product(string Name, string Category, decimal Price, int Stock);

The public properties of the Product record become the columns of the table; their names form the header row.

IXLTable table = ws.Cell("A1").InsertTable(products, "ProductTable", true);

The table is inserted at A1 and named ProductTable. The last argument creates the table as an Excel table rather than a plain range of data.

ws.Column("C").Style.NumberFormat.Format = "#,##0.00";
ws.Columns().AdjustToContents();
ws.SheetView.FreezeRows(1);

We format the prices, fit the columns to their content, and freeze the header row so that it stays visible when scrolling.

$ dotnet run
Table ProductTable at A1:D6
Columns: Name, Category, Price, Stock
Data rows: 5

Read a table into objects

The next example reads the table back into a list of records.

Program.cs
using ClosedXML.Excel;

using var wbook = new XLWorkbook("products.xlsx");

IXLTable table = wbook.Worksheet("Products").Table("ProductTable");

var products = table.DataRange.Rows()
    .Select(row => new Product(
        row.Field("Name").GetString(),
        row.Field("Category").GetString(),
        row.Field("Price").GetValue<decimal>(),
        row.Field("Stock").GetValue<int>()))
    .ToList();

foreach (var p in products)
{
    Console.WriteLine($"{p.Name,-8} {p.Category,-12} {p.Price,8:F2} {p.Stock,4}");
}

var value = products.Where(p => p.Category == "Electronics").Sum(p => p.Price * p.Stock);
Console.WriteLine($"Electronics stock value: {value:F2}");

record Product(string Name, string Category, decimal Price, int Stock);

A table is found by name with the Table method.

var products = table.DataRange.Rows()
    .Select(row => new Product(
        row.Field("Name").GetString(),
        row.Field("Category").GetString(),
        row.Field("Price").GetValue<decimal>(),
        row.Field("Stock").GetValue<int>()))
    .ToList();

DataRange is the table without its header. The Field method of a table row returns the cell of a column by its header name, so the code does not depend on the column order.

$ dotnet run
Laptop   Electronics    899.99   12
Desk     Furniture      249.50    4
Mouse    Electronics     19.90   85
Chair    Furniture      129.00    9
Monitor  Electronics    219.00   21
Electronics stock value: 17090.38

Sorting

A range can be sorted by one or more columns.

Program.cs
using ClosedXML.Excel;

using var wbook = new XLWorkbook();
var ws = wbook.Worksheets.Add("Scores");

(string, int)[] scores = [("Paul", 78), ("Lucy", 92), ("Robert", 65), ("Anna", 92), ("Tom", 81)];

ws.Cell("A1").InsertData(scores);

var range = ws.Range("A1:B5");
range.Sort("B DESC, A ASC");

foreach (var row in range.Rows())
{
    Console.WriteLine($"{row.Cell(1).Value,-7} {row.Cell(2).Value}");
}

wbook.SaveAs("sorted.xlsx");

InsertData writes a collection of tuples into rows, one item per column.

range.Sort("B DESC, A ASC");

The rows are sorted by the scores in descending order. Lucy and Anna have the same score, so the second key sorts them by name.

$ dotnet run
Anna    92
Lucy    92
Tom     81
Paul    78
Robert  65

CellsUsed

The CellsUsed method returns the cells that have a value. It works well with LINQ.

Program.cs
using ClosedXML.Excel;

using var wbook = new XLWorkbook();

var ws = wbook.Worksheets.Add("Sheet1");

string[] col1 = ["sky", "cloud", "book", "cup", "snake", "falcon"];
string[] col2 = ["in", "tool", "war", "snow", "tree", "ten"];

ws.Cell("A1").InsertData(col1);
ws.Cell("B1").InsertData(col2);

var used = ws.Range("A1:C10").CellsUsed();
Console.WriteLine($"There are {used.Count()} words in the range");

var words = used
    .Select(c => c.GetString())
    .Where(w => w.Length == 3)
    .ToList();

Console.WriteLine($"Three-letter words: {string.Join(", ", words)}");

var found = ws.CellsUsed(c => c.GetString().StartsWith('s'));
Console.WriteLine($"Starting with s: {string.Join(", ", found.Select(c => $"{c.Address}={c.Value}"))}");

wbook.SaveAs("usedcells.xlsx");

We write twelve words into two columns.

var used = ws.Range("A1:C10").CellsUsed();

The range is larger than the written data; CellsUsed skips the empty cells.

var found = ws.CellsUsed(c => c.GetString().StartsWith('s'));

An overload takes a predicate that filters the cells. The cells are visited row by row, so B4 comes before A5.

$ dotnet run
There are 12 words in the range
Three-letter words: sky, war, cup, ten
Starting with s: A1=sky, B4=snow, A5=snake

Worksheets

A workbook can contain many worksheets, which can be added, copied, renamed, moved, and deleted.

Program.cs
using ClosedXML.Excel;

using var wbook = new XLWorkbook();

foreach (string name in new[] { "Q1", "Q2", "Q3" })
{
    var ws = wbook.Worksheets.Add(name);
    ws.Cell("A1").Value = $"Report {name}";
}

wbook.Worksheet("Q1").CopyTo("Q1 copy");
wbook.Worksheet("Q3").Name = "Q3 final";
wbook.Worksheet("Q2").Delete();
wbook.Worksheet("Q3 final").Position = 1;
wbook.Worksheet("Q1").SetTabColor(XLColor.Green);

foreach (var ws in wbook.Worksheets.OrderBy(w => w.Position))
{
    Console.WriteLine($"{ws.Position}: {ws.Name} - {ws.Cell("A1").Value}");
}

wbook.SaveAs("sheets.xlsx");

We create three worksheets and change them.

wbook.Worksheet("Q1").CopyTo("Q1 copy");
wbook.Worksheet("Q3").Name = "Q3 final";
wbook.Worksheet("Q2").Delete();
wbook.Worksheet("Q3 final").Position = 1;

CopyTo copies a worksheet with its content. Setting Name renames a worksheet, and Position moves it to another tab position.

foreach (var ws in wbook.Worksheets.OrderBy(w => w.Position))

The Worksheets collection does not follow the tab order after the worksheets are moved, so we sort them by Position.

$ dotnet run
1: Q3 final - Report Q3
2: Q1 - Report Q1
3: Q1 copy - Report Q1

Source

ClosedXML GitHub page

ClosedXML documentation

In this article we have worked with Excel files in C# using the ClosedXML library.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.