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.

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()andGetDateTime(), 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
.xlsxfile. Older.xlsfiles 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):
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 inReadWithOpenXml. - Text cells return numbers like 0, 1, 2: those are shared string indexes. Look them up in the
SharedStringTable, asGetCellValuedoes. - 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’sGetDateTime(). - File is locked or in use: open it read only with
SpreadsheetDocument.Open(path, false), and for uploads read from aStreaminstead 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.

Inaccessible due to its protection level
Hello John – Could you elaborate on your question please.
What is the namespace of SpreadsheetDocument ?
Hey Satish , you will need to add below namespace
“using DocumentFormat.OpenXml.Spreadsheet”
Also additionally you may need
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
Thanks .. Helped me setup the code great way!
Thank you Martin! Glad the content helped you!
How do i format excel using above code? i mean how to add bold, number format or autosize the columns.
I need to map a model instead of using just the string
Hi Evan- You can very much do that. Please check “write excel” file part of the article, as I have used the model for the same.
I need to read a csv file that create an xlsx file with with data and graphs. Will Open XML SDK allow me to do this?
Hey David- To read CSV file , you can use other tools like explained here Read CSV files in .NET Core. Once you parse input CSV as JSON or other format , you can use OpenXML SDK for the conversion and graphs.
i need to work with dataset which contains multiple datatables and each data table should be saved into individual sheeets in single excell file.
Hi Jhansi- Thanks for your query. Please use the above Write logic for the same and extend it. It should perfectly work for your requirements. Here you should iterate over all tables from the given dataset by keeping excel handle open and each table can be written each sheet.
I need to pick particular coloumn how do i do it?
Please help
Hey Deepak- Thanks for your query! You need to iterate over the columns and set your criteria based on column name and value (if relevant) for columns you are looking for .Hope this helps!
Thank you!
Thanks Murphycn for the feedback!
Thanks for your post, it is really helpful!
Is there a way to set the width of a cell when i append it to the row? My header data is quite wide.
Hello Lilly. Glad you liked the article.
You can use Cell ‘Column’ properties to define the required width of your header. Hope this helps.
Nicely explained. Thanks.