C#
Excel
File Processing
Data Parsing
Programming

Reading Excel files from C

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Reading Excel files in C# is a frequent requirement in reporting, import pipelines, and back office tools. The main decision is choosing a library that matches your runtime constraints, file formats, and deployment environment. For server side applications, lightweight managed libraries are usually better than Office automation.

Core Sections

Choose the right library for your use case

C# applications typically use one of these strategies:

  • ExcelDataReader for fast row oriented reads.
  • ClosedXML for easier workbook and worksheet navigation.
  • EPPlus for rich .xlsx handling with a fluent API.
  • Office Interop only for desktop automation scenarios where Excel is installed.

For web services and background jobs, avoid Interop because it depends on desktop components and is not recommended for server execution.

Read .xlsx with ExcelDataReader

ExcelDataReader is efficient for ingesting tabular data and works well in import jobs.

csharp
1using System;
2using System.Data;
3using System.IO;
4using ExcelDataReader;
5
6class Program
7{
8    static void Main()
9    {
10        System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
11
12        using var stream = File.Open("sample.xlsx", FileMode.Open, FileAccess.Read);
13        using var reader = ExcelReaderFactory.CreateReader(stream);
14
15        var config = new ExcelDataSetConfiguration
16        {
17            ConfigureDataTable = _ => new ExcelDataTableConfiguration
18            {
19                UseHeaderRow = true
20            }
21        };
22
23        DataSet result = reader.AsDataSet(config);
24        DataTable sheet = result.Tables[0];
25
26        foreach (DataRow row in sheet.Rows)
27        {
28            Console.WriteLine($"Name={row["Name"]}, Amount={row["Amount"]}");
29        }
30    }
31}

This pattern is good when you need fast extraction and custom validation in application code.

Read and navigate with ClosedXML

ClosedXML gives a higher level API that is often easier to read and maintain for business logic.

csharp
1using System;
2using ClosedXML.Excel;
3
4class Program
5{
6    static void Main()
7    {
8        using var workbook = new XLWorkbook("sample.xlsx");
9        var ws = workbook.Worksheet("Sheet1");
10
11        foreach (var row in ws.RowsUsed().Skip(1))
12        {
13            string name = row.Cell(1).GetString();
14            decimal amount = row.Cell(2).GetDecimal();
15            Console.WriteLine($"{name} -> {amount}");
16        }
17    }
18}

It is ideal when worksheet structure is known and you need readable code around named sheets and cell coordinates.

Validate and map rows safely

Excel files from users often contain empty rows, unexpected headers, and type mismatches. Build a validation layer before mapping to domain objects.

csharp
1public record InvoiceRow(string Customer, decimal Total);
2
3public static bool TryMap(DataRow row, out InvoiceRow? mapped)
4{
5    mapped = null;
6
7    if (row["Customer"] is DBNull || row["Total"] is DBNull)
8        return false;
9
10    if (!decimal.TryParse(row["Total"].ToString(), out var total))
11        return false;
12
13    mapped = new InvoiceRow(row["Customer"].ToString()!, total);
14    return true;
15}

Logging rejected rows with row number and reason significantly reduces support time in production imports.

Performance and memory considerations

Large workbooks can consume substantial memory if loaded as full datasets. For high volume imports, stream rows and process incrementally, then batch writes to database. Also set practical row limits and timeouts to prevent abuse in public upload endpoints.

Common Pitfalls

  • Using Office Interop in server environments. Prefer managed libraries designed for service workloads.
  • Assuming all Excel cells contain expected types. Validate and parse defensively.
  • Reading entire workbooks into memory for huge files. Stream and process in chunks.
  • Depending on sheet index instead of stable sheet names. Use explicit workbook structure contracts.
  • Skipping error reporting for rejected rows. Return row level diagnostics for faster troubleshooting.

Summary

  • C# has multiple robust options for Excel reading, each with different tradeoffs.
  • ExcelDataReader and ClosedXML are common choices for backend import pipelines.
  • Strong validation is essential because spreadsheet input is often inconsistent.
  • Streaming and batching protect performance on large files.
  • Clear diagnostics improve reliability and user support for import workflows.

Additional implementation notes: verify configuration assumptions in staging, keep rollback paths available, and document operational choices so team members can debug issues quickly.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.