How to Read Data from Excel Sheet Using C

Cody Schneider8 min read

Pulling data from an Excel spreadsheet into a C# application is a common task, whether you're building a reporting tool, processing user uploads, or migrating legacy information. While it might seem daunting, modern libraries have made it surprisingly straightforward to access and manipulate spreadsheet data without having Excel installed on your server. This guide will walk you through a couple of the most reliable methods for reading Excel files in C#, using powerful open-source tools that can get you up and running in minutes.

GraphedGraphed

Build AI Agents for Marketing

Build virtual employees that run your go to market. Connect your data sources, deploy autonomous agents, and grow your company.

Watch Graphed demo video

Why Read Excel Files with Code?

You might be asking, "Why not just export to CSV?" While comma-separated value (CSV) files are simple and effective, they lose all the structure and richness of an Excel file. When you read an Excel file directly, you can access:

  • Multiple Worksheets: Read data from any sheet within a single workbook file.
  • Data Types: Preserve numbers, dates, and formulas instead of treating everything as a string.
  • Formatting (optional): Access cell colors, font styles, and other formatting if your application requires it.
  • Named Ranges: Target specific data sets within a sheet without relying on fixed row and column numbers.

Automating this process is a huge time-saver. Imagine a workflow where sales reps upload their weekly reports as Excel files. A C# application could automatically pick up these files, read the data, and insert it into a central database without anyone lifting a finger.

Setting the Stage: What You Need to Know

Before jumping into the code, it’s helpful to understand the landscape. There are two primary Excel file formats you'll encounter:

  • .xls: The older, binary format used by Excel versions from 97 to 2003. This format is more complex to work with programmatically.
  • .xlsx: The modern format introduced in Excel 2007. It's an XML-based format (specifically, Office Open XML), essentially a ZIP archive containing XML files that describe the workbook's content and structure.

Most modern libraries are designed to work with the .xlsx format because it’s an open standard and much easier to parse. For this tutorial, we will focus exclusively on reading .xlsx files.

Dependencies are Your Friend

While you could theoretically unzip an .xlsx file and parse the raw XML yourself, it would be an incredible amount of work. Instead, we'll use NuGet packages - libraries created by the community that handle all the heavy lifting for us. To install these in Visual Studio, you can either use the NuGet Package Manager Console or the UI:

  • Package Manager Console: Go to Tools > NuGet Package Manager > Package Manager Console and type the Install-Package command.
  • NuGet Package Manager UI: Right-click on your project in the Solution Explorer and select "Manage NuGet Packages...". From there, you can search for and install the package you need.

Method 1: Using EPPlus - A Powerful Community Favorite

EPPlus is one of the most popular and feature-rich libraries for working with .xlsx files in the .NET ecosystem. It gives you full control over reading, writing, and manipulating Excel files without any dependency on Microsoft Office.

Free PDF · the crash course

AI Agents for Marketing Crash Course

Learn how to deploy AI marketing agents across your go-to-market — the best tools, prompts, and workflows to turn your data into autonomous execution without writing code.

A Quick Note on EPPlus Licensing

It's important to know that starting with version 5, EPPlus moved to a dual-license model. It is free for non-commercial use under the PolyForm Noncommercial license. If you're building a commercial application, you'll need to purchase a commercial license. We'll use the free license for this example.

Step 1: Installing EPPlus

Open the Package Manager Console and run the following command:

Install-Package EPPlus

Step 2: Preparing a Sample Excel File

Create an Excel file named Employees.xlsx and save it somewhere your application can access it (like the project's debug folder). Add some data to the first worksheet like this:

Make sure to format the HireDate column as a date in Excel.

Step 3: Writing the C# Code to Read the Data

Now, let's write the C# code. This example reads the data from Employees.xlsx and prints it to the console.

using OfficeOpenXml, using System.IO,

public class ExcelReader { public static void ReadWithEPPlus(string filePath) { // Set the license context for EPPlus ExcelPackage.LicenseContext = LicenseContext.NonCommercial,

    var fileInfo = new FileInfo(filePath),

    if (!fileInfo.Exists)
    {
        throw new FileNotFoundException($"File not found at: {filePath}"),
    }

    using (var package = new ExcelPackage(fileInfo))
    {
        // Get the first worksheet in the workbook
        ExcelWorksheet worksheet = package.Workbook.Worksheets[0],

        if (worksheet == null)
        {
            Console.WriteLine("No worksheet found in the file."),
            return,
        }

        // Get the dimensions of the worksheet
        int startRow = worksheet.Dimension.Start.Row,
        int endRow = worksheet.Dimension.End.Row,
        int startCol = worksheet.Dimension.Start.Column,
        int endCol = worksheet.Dimension.End.Column,

        Console.WriteLine($"Reading data from: {worksheet.Name}"),
        Console.WriteLine(new string('-', 30)),

        // Loop through the rows and columns
        for (int row = startRow + 1, row <= endRow, row++) // Start from row 2 to skip headers
        {
            for (int col = startCol, col <= endCol, col++)
            {
                // Get cell value - .Value is of type object
                object cellValue = worksheet.Cells[row, col].Value,

                // It's good practice to handle null values
                Console.Write((cellValue?.ToString() ?? "NULL") + "\t"),
            }
            Console.WriteLine(), // New line for the next row
        }
    }
}

}

To run this, make sure you call the method from your Main function, providing the correct path to your Employees.xlsx file.

GraphedGraphed

Build AI Agents for Marketing

Build virtual employees that run your go to market. Connect your data sources, deploy autonomous agents, and grow your company.

Watch Graphed demo video

Method 2: Using ClosedXML - A Simpler, MIT-Licensed Alternative

ClosedXML is another fantastic library for handling .xlsx files. It acts as a friendly wrapper around the official Open XML SDK, providing a cleaner and more intuitive API for common operations. A big advantage of ClosedXML is its MIT license, which makes it completely free for both commercial and non-commercial use.

Step 1: Installing ClosedXML

In the Package Manager Console, run:

Install-Package ClosedXML

Step 2: Writing the C# Code

The code for ClosedXML is similarly straightforward. It has some convenient methods like .RowsUsed() which lets you iterate only over the rows that contain data, saving you from navigating empty portions of a sheet.

using ClosedXML.Excel, using System.IO,

public class ExcelReader { public static void ReadWithClosedXML(string filePath) { if (!File.Exists(filePath)) { throw new FileNotFoundException($"File not found at: {filePath}"), }

    // Open the workbook
    using (var workbook = new XLWorkbook(filePath))
    {
        // Get the first worksheet
        var worksheet = workbook.Worksheet(1), // Worksheets are 1-based

        if (worksheet == null)
        {
            Console.WriteLine("No worksheet found at index 1."),
            return,
        }
        
        Console.WriteLine($"Reading data from: {worksheet.Name}"),
        Console.WriteLine(new string('-', 30)),
        
        // Get all rows that have data (skipping the header row with .RowsUsed().Skip(1))
        var rows = worksheet.RowsUsed().Skip(1),

        foreach (var row in rows)
        {
            // Reading data from specific cells in the current row
            string employeeId = row.Cell(1).GetValue<string>(),
            string fullName = row.Cell(2).GetValue<string>(),
            string department = row.Cell(3).GetValue<string>(),
            string hireDate = row.Cell(4).GetValue<DateTime>().ToShortDateString(),

            Console.WriteLine($"{employeeId}\t{fullName}\t{department}\t{hireDate}"),
        }
    }
}

}

Notice how ClosedXML's .GetValue<T>() method allows you to specify the expected data type directly, which helps avoid casting issues and makes the code very clear.

Free PDF · the crash course

AI Agents for Marketing Crash Course

Learn how to deploy AI marketing agents across your go-to-market — the best tools, prompts, and workflows to turn your data into autonomous execution without writing code.

What About Old-School Methods like ODBC or OLE DB?

You may also come across older articles suggesting the use of OLE DB or ODBC drivers to read Excel files. This approach involves installing the Microsoft Access Database Engine and then using C# to connect to the Excel file as if it were a database. You can then use SQL queries like SELECT * FROM [Sheet1$] to retrieve data.

While this method works, it has some significant drawbacks compared to modern libraries:

  • Driver Dependencies: It requires a specific driver to be installed on any machine that runs your code. This complicates deployment, and you often run into headaches with 32-bit vs. 64-bit compatibility.
  • Less Control: You lose the fine-grained control over the spreadsheet that libraries like EPPlus and ClosedXML provide. You are essentially limited to what you can do with basic SQL.
  • Feels Outdated: Library-based approaches are generally considered the standard for modern .NET development.

For these reasons, sticking with a dedicated library like EPPlus or ClosedXML is almost always the better choice for new projects.

Final Thoughts

Reading Excel files in C# has become a simple and robust process thanks to powerful open-source libraries. Both EPPlus and ClosedXML abstract away the complexity of the underlying file format, allowing you to focus on working with the data itself. By choosing the right tool, you can easily automate data imports and integrate spreadsheet-based workflows directly into your applications.

For those of us working with data from many different sources, we know that automating data collection is a huge win. That’s why we built Graphed to eliminate the manual work of pulling reports from platforms like Google Analytics, Shopify, Facebook Ads, and dozens of others. Instead of writing code to parse files from each source, you can connect your accounts in seconds and use simple natural language to generate real-time dashboards and reports. To see how much faster you can get insights, give Graphed a try.

Related Articles