TheCodeBuzz

Best Practices for Software Development

  • Home
  • Series
    • .NET Core
    • Design Pattern
    • Code Smell
    • Angular
    • React
    • Vue.js
    • IoT
  • Tools
  • About

Read Excel Files in C# .NET (Open XML SDK, ClosedXML)

Home >.NET Core>Read Excel Files in C# .NET (Open XML SDK, ClosedXML)
Read Excel Files in C# .NET (Open XML SDK, ClosedXML)

You have an .xlsx file from finance or a customer, and your .NET app needs the rows inside it. Maybe it is an import job, maybe an upload endpoint. You do not want to install Excel on the server, and you do not want a library that silently drops the empty cells.

You can read an Excel file in C# with the free Open XML SDK from Microsoft (official docs) or with ClosedXML. Neither needs Microsoft Office. The code below was built and run on .NET 10 with DocumentFormat.OpenXml 3.5.1 and ClosedXML 0.105.1, and works the same way on .NET 8 and 9.

The one trap is empty cells. Here is what happens inside the file, and the code that handles it follows.

Animation showing that empty Excel cells are missing from the Open XML cell list and are mapped back to columns using the cell reference, then converted to JSON
Empty cells are not stored, so match each cell to its column by reference.
  • Which approach should you choose?
  • Prerequisites
  • Step 1: Create a sample workbook
  • Step 2, option A: Read Excel with the Open XML SDK
  • Step 2, option B: Read Excel with ClosedXML
  • Read Excel as JSON
  • What the output looks like
  • Common problems and fixes
  • Frequently asked questions
  • Summary

Which approach should you choose?

  • Open XML SDK: official Microsoft package, no third-party dependency, full control and low memory use. You write more code and must handle shared strings and empty cells yourself.
  • ClosedXML: much shorter code, typed getters such as GetDouble() and GetDateTime(), and empty cells are handled for you. Best for most apps.
  • Prefer another library? See Read/Write Excel using EPPlus (commercial license for business use) or Read/Write Excel using NPOI.

Prerequisites

  • A .NET 8, 9 or 10 project (a console app is enough).
  • An .xlsx file. Older .xls files are not supported by these two libraries; use NPOI for those.
dotnet add package DocumentFormat.OpenXml
dotnet add package ClosedXML

Step 1: Create a sample workbook

To keep the example self-contained, this method writes a small employees.xlsx with ClosedXML. It leaves one name and one salary empty on purpose, which is the case that breaks most readers. You can skip it and use your own file.

public static void WriteSample(string path)
{
    using var wb = new XLWorkbook();
    var ws = wb.Worksheets.Add("Employees");
    ws.Cell("A1").Value = "Id";
    ws.Cell("B1").Value = "Name";
    ws.Cell("C1").Value = "Salary";
    ws.Cell("D1").Value = "Joined";
    ws.Cell("A2").Value = 1; ws.Cell("B2").Value = "Asha";  ws.Cell("C2").Value = 5200.5; ws.Cell("D2").Value = new DateTime(2022, 3, 14);
    ws.Cell("A3").Value = 2; /* B3 left empty */              ws.Cell("C3").Value = 4800;   ws.Cell("D3").Value = new DateTime(2023, 1, 9);
    ws.Cell("A4").Value = 3; ws.Cell("B4").Value = "Asha";  /* C4 empty */                  ws.Cell("D4").Value = new DateTime(2024, 7, 1);
    wb.SaveAs(path);
}

Step 2, option A: Read Excel with the Open XML SDK

Two details matter. Shared strings: text cells store only an index, and the text lives in the shared string table. Empty cells: Excel omits them from the XML, so read the column from CellReference (such as B3) and pad the gap instead of trusting the cell order.

using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;

public static string GetColumn(string cellRef) => new string(cellRef.TakeWhile(char.IsLetter).ToArray());

public static int ColumnIndex(string col) => col.Aggregate(0, (a, c) => a * 26 + (c - 'A' + 1)) - 1;

public static List<string[]> ReadWithOpenXml(string path)
{
    var result = new List<string[]>();
    using var doc = SpreadsheetDocument.Open(path, false);
    var wbPart = doc.WorkbookPart!;
    var sst = wbPart.SharedStringTablePart?.SharedStringTable;
    var sheet = wbPart.Workbook!.Descendants<Sheet>().First();
    var wsPart = (WorksheetPart)wbPart.GetPartById(sheet.Id!);

    foreach (var row in wsPart.Worksheet!.Descendants<Row>())
    {
        var values = new List<string>();
        foreach (var cell in row.Elements<Cell>())
        {
            // Excel skips empty cells, so use the cell reference (B3) to find the column
            int index = ColumnIndex(GetColumn(cell.CellReference!.Value!));
            while (values.Count < index) values.Add("");
            values.Add(GetCellValue(cell, sst));
        }
        result.Add(values.ToArray());
    }
    return result;
}

public static string GetCellValue(Cell cell, SharedStringTable? sst)
{
    var raw = cell.CellValue?.InnerText ?? cell.InnerText;
    if (cell.DataType?.Value == CellValues.SharedString && sst != null)
        return sst.ElementAt(int.Parse(raw)).InnerText;
    if (cell.DataType?.Value == CellValues.Boolean) return raw == "1" ? "TRUE" : "FALSE";
    return raw;
}

Call it with foreach (var row in ReadWithOpenXml("employees.xlsx")) Console.WriteLine(string.Join(" | ", row));. Rows with fewer cells at the end are shorter arrays; pad them if you need a fixed width.

Step 2, option B: Read Excel with ClosedXML

ClosedXML reads the sheet as a range. GetString() returns an empty string for an empty cell, and IsEmpty() lets you map it to null instead.

using ClosedXML.Excel;
using System.Globalization;

public static void ReadWithClosedXml(string path)
{
    using var wb = new XLWorkbook(path);
    var ws = wb.Worksheet(1);
    foreach (var row in ws.RangeUsed()!.RowsUsed().Skip(1))
    {
        var id = row.Cell(1).GetValue<int>();
        var name = row.Cell(2).GetString();                // "" when empty
        var salary = row.Cell(3).IsEmpty() ? (double?)null : row.Cell(3).GetDouble();
        var joined = row.Cell(4).GetDateTime();
        Console.WriteLine($"{id} | {name} | {salary?.ToString(CultureInfo.InvariantCulture) ?? "null"} | {joined:yyyy-MM-dd}");
    }
}

Read Excel as JSON

Use the header row as property names and serialize with System.Text.Json. Empty cells become null, numbers stay numbers and dates stay dates. If you need to do this with the Open XML SDK only, see Read Excel as JSON using the Open XML SDK. To send the result to a client, see Return and download a file from an ASP.NET Core Web API.

using System.Text.Json;
using ClosedXML.Excel;

public static string ToJson(string path)
{
    using var wb = new XLWorkbook(path);
    var ws = wb.Worksheet(1);
    var range = ws.RangeUsed()!;
    var headers = range.FirstRow().Cells().Select(c => c.GetString()).ToList();
    var rows = new List<Dictionary<string, object?>>();
    foreach (var r in range.RowsUsed().Skip(1))
    {
        var item = new Dictionary<string, object?>();
        for (int i = 0; i < headers.Count; i++)
        {
            var c = r.Cell(i + 1);
            item[headers[i]] = c.IsEmpty() ? null : c.Value.Type switch
            {
                XLDataType.Number => c.GetDouble(),
                XLDataType.DateTime => c.GetDateTime(),
                XLDataType.Boolean => c.GetBoolean(),
                _ => c.GetString()
            };
        }
        rows.Add(item);
    }
    return JsonSerializer.Serialize(rows, new JsonSerializerOptions { WriteIndented = true });
}

What the output looks like

Running all three readers on the sample file printed this (the Open XML version shows the raw date serial; see the fixes below):

— Open XML SDK — Id | Name | Salary | Joined 1 | Asha | 5200.5 | 44634 2 | | 4800 | 44935 3 | Asha | | 45474 — ClosedXML — 1 | Asha | 5200.5 | 2022-03-14 2 | | 4800 | 2023-01-09 3 | Asha | null | 2024-07-01 — JSON — [ { "Id": 1, "Name": "Asha", "Salary": 5200.5, "Joined": "2022-03-14T00:00:00" }, { "Id": 2, "Name": null, "Salary": 4800, "Joined": "2023-01-09T00:00:00" }, { "Id": 3, "Name": "Asha", "Salary": null, "Joined": "2024-07-01T00:00:00" } ]

The JSON is shown on fewer lines here for readability; the program prints it indented. The empty name and salary stay in the right columns.

Common problems and fixes

  • Values shift left after an empty cell: you used the cell order instead of CellReference. Use the column index as shown in ReadWithOpenXml.
  • Text cells return numbers like 0, 1, 2: those are shared string indexes. Look them up in the SharedStringTable, as GetCellValue does.
  • Dates appear as 44634: Excel stores dates as serial numbers. With the Open XML SDK convert with DateTime.FromOADate(double.Parse(value, CultureInfo.InvariantCulture)) when the cell has a date format, or use ClosedXML’s GetDateTime().
  • File is locked or in use: open it read only with SpreadsheetDocument.Open(path, false), and for uploads read from a Stream instead of saving to disk.
  • Very large files use a lot of memory: the code above loads each sheet as a DOM. For hundreds of thousands of rows use the Open XML SDK’s OpenXmlReader (streaming).

Frequently asked questions

Do I need Microsoft Office installed to read an Excel file in C#?

No. The Open XML SDK and ClosedXML read the .xlsx file directly, so no Excel installation is needed on servers or in Docker.

How do I read a specific sheet or cell?

With ClosedXML use wb.Worksheet("Employees").Cell("B2").GetString(). With the Open XML SDK pick the Sheet by its Name and find the cell whose CellReference matches.

Can I read .xls files with these libraries?

No. They support the .xlsx format only. For the older .xls format use NPOI, covered in the NPOI post linked above.

Summary

To read an Excel file in C#, use ClosedXML for short, typed code, or the Open XML SDK when you want no third-party dependency. Handle shared strings, read columns from the cell reference so empty cells do not shift values, and convert date serials. Tested here: reading, empty cells, JSON output and writing the sample file. Not tested: .xls files, very large files, password-protected workbooks and formulas that depend on other files.

Found this useful?

Bookmark this page and share it with your team. Get new .NET, cloud and database tutorials in your inbox.

Subscribe to TheCodeBuzz
facebookShare on Facebook
TwitterPost on X
FollowFollow us
PinterestSave

Post navigation

How to Explore Docker container’s file system
How to use Visual Studio IntelliCode – Code Development using AI
blank
get-free-ebook-micro-services-guideline

©TheCodeBuzz 2026. All rights reserved. Privacy Policy.

To serve the best User Experience on the website, we use essential cookies. By clicking “Continue”, Please give consent to our privacy policy.
SettingsContinue to Site
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
CookieDurationDescription
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
SAVE & ACCEPT
RSS
Follow by Email
Facebook
fb-share-icon
X (Twitter)
Post on X
LinkedIn
Share