skip to content
Stylized letter A in teal with pink sparkle accents Khalid Abuhakmeh

Read and Write Excel Files in C# (.xlsx)

/ 6 min read

Updated:

Microsoft Excel is the undisputed champion of the business world, powering every industry and informing decision-makers at the highest echelons of corporate structures. As a developer, it is not a matter of if we’ll have to deal with Excel spreadsheets, but a matter of when. Fret not! This post will look at the most straightforward way I’ve found reading and writing Excel spreadsheets using C# and the .NET runtime.

Bottom line: the simplest way to read and write .xlsx files in C# is the ExcelMapper NuGet package. It maps Excel rows directly to your C# records or POCOs, works cross-platform without Microsoft Office installed, and needs only a few lines of code for both reading and writing.

Which C# Library Should I Use for Excel?

ExcelMapper is my go-to for quick, code-first reads and writes, but it’s not the only option. Here’s a quick comparison so you can pick the right tool for your project.

Library Best for
ExcelMapper Mapping Excel rows straight to POCOs/records with minimal code; built on NPOI.
NPOI Lower-level, full control over workbooks, formatting, and formulas; free and OSS.
ClosedXML A friendlier, fluent API over OpenXML for building richly formatted workbooks; free and OSS.
EPPlus Feature-rich formula and formatting support, but commercial/paid licensing since version 5.

If you just need to shuttle data in and out of .xlsx files, start with ExcelMapper. If you need fine-grained formatting control, look at ClosedXML or NPOI directly.

ExcelMapper

ExcelMapper is an MIT-licensed .NET OSS package that allows us to read and write Excel files using “Plain old C# objects (POCOs)”. The library works cross-platform using a purely managed NPOI library instead of the Jet database engine found exclusively on Windows devices — so you don’t need Microsoft Office installed to read or write Excel files. Those familiar with other data access libraries will find using ExcelMapper reminiscent of libraries like Entity Framework Core or Dapper. Users can also work with dynamic objects and records, so you can lean on modern .NET features. ExcelMapper also supports Excel concepts like formulas, formatting, and sheets.

How to Read an Excel File in C#

Let’s say we have an Excel file that contains data about movies. The header column includes values for Id, Name, and StreamingService. ExcelMapper can create dynamic mappings based on our columns, so we only need to create a record that matches our column names.

public record Movie(
int Id,
string Name,
string StreamingService
);

The next step is to create an instance of ExcelMapper and then call the FetchAsync method with our record type.

const string excelFile = "Movies.xlsx";
var excel = new ExcelMapper();
var movies = (await excel.FetchAsync<Movie>(excelFile)).ToList();

Now we can use our movies in a foreach loop.

foreach (var movie in movies)
{
Console.WriteLine(movie);
}

Running our application, we can see the results in our console output.

Terminal window
Movie { Id = 2, Name = Ted, StreamingService = netflix }
Movie { Id = 5, Name = The Giver, StreamingService = netflix }
Movie { Id = 12, Name = Underworld: Awakening, StreamingService = netflix }
Movie { Id = 17, Name = The Boondock Saints, StreamingService = netflix }
Movie { Id = 24, Name = The Princess and the Frog, StreamingService = netflix }
Movie { Id = 30, Name = Let's Be Cops, StreamingService = netflix }
Movie { Id = 31, Name = We're the Millers, StreamingService = netflix }
Movie { Id = 34, Name = Saw III, StreamingService = netflix }
Movie { Id = 35, Name = The Imitation Game, StreamingService = netflix }
Movie { Id = 38, Name = Transformers: Age of Extinction, StreamingService = netflix }

How to Write to an Excel File in C#

Writing an .xlsx file is just as straightforward as reading one. Like reading from an Excel file, we’ll first need to create an instance of ExcelMapper. Let’s take our first example and alter the StreamingService column and then write it to a new sheet labeled disney+. Since we’re using C# 9 records, we’ll use the with keyword to create duplicate instances.

using System;
using System.Collections.Generic;
using System.Linq;
using Ganss.Excel;
const string excelFile = "Movies.xlsx";
var excel = new ExcelMapper();
var movies = (await excel.FetchAsync<Movie>(excelFile)).ToList();
var purchasedByDisney = new List<Movie>();
const string disney = "disney+";
foreach (var movie in movies)
{
Console.WriteLine(movie);
purchasedByDisney.Add(movie with
{
StreamingService = disney
});
}
await excel.SaveAsync(
excelFile,
purchasedByDisney,
sheetName: disney
);
public record Movie(
int Id,
string Name,
string StreamingService
);

After executing our program, we can see we have a new sheet labeled disney+ in our favorite spreadsheet viewer.

excel spreadsheets in numbers showing new sheet

Wow, it doesn’t get any easier than that!

Writing a Brand-New Workbook

The example above updates an existing workbook, but SaveAsync works just as well against a file that doesn’t exist yet — ExcelMapper will create it for you. That means you can go from an in-memory List<T> to a downloadable .xlsx file with a single call:

var newReleases = new List<Movie>
{
new(100, "Dune: Part Two", "max"),
new(101, "Oppenheimer", "peacock")
};
var excel = new ExcelMapper();
await excel.SaveAsync("NewReleases.xlsx", newReleases);

No workbook object to configure and no cell-by-cell writing. If your data already lives in C# objects, this is the fastest path to a spreadsheet.

FAQ

How do I write to an .xlsx file in C#?

Create a List<T> of your records, instantiate new ExcelMapper(), and call await excel.SaveAsync(path, data). ExcelMapper will create the file if it doesn’t exist or write a new sheet if you pass a sheetName.

Can I read Excel without Microsoft Office installed?

Yes. ExcelMapper (and the NPOI library it’s built on) is pure managed .NET code, so it reads and writes .xlsx files cross-platform without Excel, Office, or any COM interop installed.

What’s the best C# library to write Excel files?

For quick, code-first reads and writes, ExcelMapper is the easiest option because it maps rows to POCOs directly. For heavier formatting and formula needs, consider ClosedXML (free) or EPPlus (commercial since v5).

Conclusion

ExcelMapper allows .NET developers to focus on data while still giving them access to the features that make Excel a great all-purpose tool. Read existing data into POCOs, manipulate rows, and write it back any way you like. In a few lines of C# 9, we can do all we want with minimal effort. That’ll keep the business folks in our lives that much happier.

If you’re exporting data in other formats, check out my posts on converting C# objects to CSV and other formats, reading files in C#, and templating Microsoft Word documents with MiniWord.

Thanks for reading, and please leave a comment below. Also, follow me on Mastodon at @khalidabuhakmeh to get the latest .NET news and tutorials.

Related Posts