Skip to footer content
USING IRONXL

How to Open Excel Files in C# with IronXL

Opening and working with Excel files in C# is something nearly every .NET developer encounters sooner or later. Whether you are automating weekly reports, processing data imports, or building tools that generate spreadsheets on the fly, the library you choose can make a significant difference in speed, reliability, and deployment flexibility.

This tutorial walks through how to open Excel files in C# using IronXL -- a lightweight Excel library that reads, edits, and writes workbooks without requiring Microsoft Office to be installed. You will see how simple it is to load data, access worksheets, and work with cells programmatically, all inside your C# application.

Why Choose IronXL Over Microsoft.Office.Interop.Excel?

While Microsoft.Office.Interop.Excel has been the traditional approach for Excel automation, it comes with significant limitations that make IronXL the better choice for modern applications. Microsoft itself recommends against using Office Interop on servers, citing instability, scalability issues, and unsupported deployment scenarios.

IronXL vs Microsoft.Office.Interop.Excel feature comparison
Feature IronXL Microsoft.Office.Interop.Excel
Excel Installation Required No Yes
Cross-Platform Support Windows, Linux, macOS Windows only
Server Deployment Fully supported Not recommended by Microsoft
Memory Management Automatic Manual COM cleanup required
API Complexity Simple and intuitive Complex COM interfaces
File Format Support XLS, XLSX, CSV, TSV, JSON Limited to Excel formats
Thread Safety Supported Single-threaded only

IronXL eliminates the dependency on Microsoft Excel, making it ideal for server environments, Docker containers, and cloud platforms like Azure. The library provides a clean, modern API that removes the need to deal with COM objects or manual memory management. Beyond opening files, IronXL handles everything from formula evaluation to chart generation to cell styling.

How Do You Install IronXL in a .NET Project?

Getting started with IronXL is straightforward -- it can be added to your project in minutes via the NuGet Package Manager. Open the Package Manager Console in Visual Studio and run:

Install-Package IronXL
dotnet add package IronXL
Install-Package IronXL
dotnet add package IronXL
SHELL

Both commands install the same package. Use the first in the Visual Studio Package Manager Console, and the second with the .NET CLI. After installation, you can verify the package reference appears in your project file under <PackageReference Include="IronXL.Excel" />.

Get stated with IronXL now.
green arrow pointer

What .NET Versions Does IronXL Support?

IronXL targets the full spectrum of modern .NET versions, including .NET 10, .NET 8, .NET 6, .NET Framework 4.6.2 and above, and .NET Standard 2.0. This breadth of support means you can use IronXL in new projects targeting .NET 10 as well as legacy applications running on the traditional .NET Framework.

The library is available as a single NuGet package that automatically selects the correct binary for your target framework. No additional dependencies, no platform-specific installs, and no Excel license required. Visit the IronXL compatibility guide for a complete list of supported runtimes and platforms.

How Do You Open and Read an Existing Excel File in C#?

Opening existing Excel files with IronXL requires just a few lines of code. The library supports reading XLS and XLSX files, as well as CSV and TSV formats, through a unified API. The following example demonstrates the essential workflow:

// Load an existing Excel file
WorkBook workbook = WorkBook.Load("sales-data.xlsx");

// Access the first worksheet by index
WorkSheet sheet = workbook.WorkSheets[0];

// Or access a worksheet by name
WorkSheet namedSheet = workbook.GetWorkSheet("January Sales");

// Read a specific cell value
string cellValue = sheet["A1"].StringValue;
Console.WriteLine($"Cell A1 contains: {cellValue}");

// Read a numeric value
decimal revenue = sheet["B2"].DecimalValue;
Console.WriteLine($"Revenue: {revenue:C}");

// Check cell data type before reading
var cell = sheet["C3"];
Console.WriteLine($"Type: {cell.Type}, Value: {cell.Value}");
// Load an existing Excel file
WorkBook workbook = WorkBook.Load("sales-data.xlsx");

// Access the first worksheet by index
WorkSheet sheet = workbook.WorkSheets[0];

// Or access a worksheet by name
WorkSheet namedSheet = workbook.GetWorkSheet("January Sales");

// Read a specific cell value
string cellValue = sheet["A1"].StringValue;
Console.WriteLine($"Cell A1 contains: {cellValue}");

// Read a numeric value
decimal revenue = sheet["B2"].DecimalValue;
Console.WriteLine($"Revenue: {revenue:C}");

// Check cell data type before reading
var cell = sheet["C3"];
Console.WriteLine($"Type: {cell.Type}, Value: {cell.Value}");
$vbLabelText   $csharpLabel

The WorkBook.Load() method automatically detects the file format -- XLS, XLSX, CSV, or TSV -- and handles parsing without any additional configuration. You access worksheets either by index using workbook.WorkSheets[0] or by name using GetWorkSheet(). Individual cell values are readable through bracket notation (sheet["A1"]), making the code concise and expressive. For the full list of supported file types, see the Open XML SDK documentation on SpreadsheetML and the IronXL NuGet package page.

For typed access, IronXL exposes properties like .StringValue, .DecimalValue, .IntValue, .BoolValue, and .DateTimeValue directly on cells. This eliminates the type guessing common with generic object-based APIs. For more complex scenarios, visit the working with Excel ranges guide and the cell data formats documentation.

Output

How to Open Excel Files Application in C# Using IronXL: Figure 1 - Opening and reading a sample Excel file

How Do You Load Excel Files From a Stream or Byte Array?

In web applications and cloud functions, you often receive file data as a stream or byte array rather than a file path. IronXL handles both cases:

// Load from a byte array (e.g., from a database or HTTP response)
byte[] fileBytes = File.ReadAllBytes("sales-data.xlsx");
WorkBook workbookFromBytes = WorkBook.Load(fileBytes);

// Load from a MemoryStream
using var memStream = new MemoryStream(fileBytes);
WorkBook workbookFromStream = WorkBook.Load(memStream);

// Access data the same way regardless of source
WorkSheet sheet = workbookFromStream.DefaultWorkSheet;
Console.WriteLine(sheet["A1"].StringValue);
// Load from a byte array (e.g., from a database or HTTP response)
byte[] fileBytes = File.ReadAllBytes("sales-data.xlsx");
WorkBook workbookFromBytes = WorkBook.Load(fileBytes);

// Load from a MemoryStream
using var memStream = new MemoryStream(fileBytes);
WorkBook workbookFromStream = WorkBook.Load(memStream);

// Access data the same way regardless of source
WorkSheet sheet = workbookFromStream.DefaultWorkSheet;
Console.WriteLine(sheet["A1"].StringValue);
$vbLabelText   $csharpLabel

Stream-based loading is particularly useful in ASP.NET Core controllers where you receive an IFormFile upload. Simply call formFile.OpenReadStream() and pass the result to WorkBook.Load(). For complete ASP.NET Core integration patterns, see the ASP.NET Core Excel tutorial.

How Do You Create New Excel Workbooks in C#?

Creating new Excel files is equally straightforward with IronXL's spreadsheet creation capabilities. The following example builds a formatted quarterly report:

// Create a new workbook in XLSX format
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);

// Add metadata
workbook.Metadata.Author = "Sales Department";
workbook.Metadata.Title = "Q1 Revenue Report";

// Create a named worksheet
WorkSheet sheet = workbook.CreateWorkSheet("Q1 Report");

// Add header row
sheet["A1"].Value = "Product";
sheet["B1"].Value = "Units Sold";
sheet["C1"].Value = "Revenue";

// Add data rows
sheet["A2"].Value = "Software Licenses";
sheet["B2"].Value = 120;
sheet["C2"].Value = 45000;

sheet["A3"].Value = "Support Contracts";
sheet["B3"].Value = 55;
sheet["C3"].Value = 27500;

// Add a SUM formula
sheet["C4"].Formula = "=SUM(C2:C3)";

// Apply number formatting
sheet["C2:C4"].FormatString = "$#,##0.00";

// Save the workbook to disk
workbook.SaveAs("quarterly-report.xlsx");
Console.WriteLine("Workbook saved successfully.");
// Create a new workbook in XLSX format
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);

// Add metadata
workbook.Metadata.Author = "Sales Department";
workbook.Metadata.Title = "Q1 Revenue Report";

// Create a named worksheet
WorkSheet sheet = workbook.CreateWorkSheet("Q1 Report");

// Add header row
sheet["A1"].Value = "Product";
sheet["B1"].Value = "Units Sold";
sheet["C1"].Value = "Revenue";

// Add data rows
sheet["A2"].Value = "Software Licenses";
sheet["B2"].Value = 120;
sheet["C2"].Value = 45000;

sheet["A3"].Value = "Support Contracts";
sheet["B3"].Value = 55;
sheet["C3"].Value = 27500;

// Add a SUM formula
sheet["C4"].Formula = "=SUM(C2:C3)";

// Apply number formatting
sheet["C2:C4"].FormatString = "$#,##0.00";

// Save the workbook to disk
workbook.SaveAs("quarterly-report.xlsx");
Console.WriteLine("Workbook saved successfully.");
$vbLabelText   $csharpLabel

The WorkBook.Create() method initializes a new workbook in the specified format. You can add multiple worksheets using CreateWorkSheet(), populate cells with various data types including strings, numbers, booleans, and dates, and apply Excel formulas directly through the Formula property. The library handles data type conversion and Excel-specific formatting requirements automatically.

For styling headers and adding borders, use the cell styling API. For template-based report generation, see the export from existing Excel templates guide.

Output

How to Open Excel Files Application in C# Using IronXL: Figure 2 - Creating new Excel workbooks

How Do You Read and Process Excel Worksheet Data in Bulk?

IronXL handles data extraction and bulk processing efficiently through range-based operations and DataTable conversion:

// Load a workbook and select the default sheet
WorkBook workbook = WorkBook.Load("inventory.xlsx");
WorkSheet sheet = workbook.DefaultWorkSheet;

// Read a rectangular range of cells
var range = sheet["A1:D10"];
foreach (var cell in range)
{
    Console.WriteLine($"{cell.AddressString}: {cell.Text}");
}

// Convert the worksheet to a DataTable for database integration
System.Data.DataTable dataTable = sheet.ToDataTable(useFirstRowAsColumnHeaders: true);
Console.WriteLine($"Rows: {dataTable.Rows.Count}, Columns: {dataTable.Columns.Count}");

// Use aggregate functions directly on a range
decimal total = sheet["C2:C10"].Sum();
decimal average = sheet["C2:C10"].Avg();
decimal maxValue = sheet["C2:C10"].Max();

Console.WriteLine($"Total: {total:C}");
Console.WriteLine($"Average: {average:C}");
Console.WriteLine($"Max: {maxValue:C}");

// Filter and find rows using LINQ on the DataTable
var highValue = dataTable.AsEnumerable()
    .Where(row => row.Field<decimal>("Revenue") > 10000)
    .ToList();
Console.WriteLine($"High-value rows: {highValue.Count}");
// Load a workbook and select the default sheet
WorkBook workbook = WorkBook.Load("inventory.xlsx");
WorkSheet sheet = workbook.DefaultWorkSheet;

// Read a rectangular range of cells
var range = sheet["A1:D10"];
foreach (var cell in range)
{
    Console.WriteLine($"{cell.AddressString}: {cell.Text}");
}

// Convert the worksheet to a DataTable for database integration
System.Data.DataTable dataTable = sheet.ToDataTable(useFirstRowAsColumnHeaders: true);
Console.WriteLine($"Rows: {dataTable.Rows.Count}, Columns: {dataTable.Columns.Count}");

// Use aggregate functions directly on a range
decimal total = sheet["C2:C10"].Sum();
decimal average = sheet["C2:C10"].Avg();
decimal maxValue = sheet["C2:C10"].Max();

Console.WriteLine($"Total: {total:C}");
Console.WriteLine($"Average: {average:C}");
Console.WriteLine($"Max: {maxValue:C}");

// Filter and find rows using LINQ on the DataTable
var highValue = dataTable.AsEnumerable()
    .Where(row => row.Field<decimal>("Revenue") > 10000)
    .ToList();
Console.WriteLine($"High-value rows: {highValue.Count}");
$vbLabelText   $csharpLabel

The range selection syntax (sheet["A1:D10"]) provides an elegant way to work with multiple cells at once. The ToDataTable() method converts worksheet data into a System.Data.DataTable, which integrates directly with Entity Framework, data binding controls, and SQL bulk copy operations. IronXL also supports aggregate functions -- Sum(), Avg(), Max(), and Min() -- directly on ranges, eliminating the need to write manual iteration code.

For handling very large datasets efficiently, consult the complete IronXL API reference for streaming and chunked processing patterns.

How to Open Excel Files Application in C# Using IronXL: Figure 3 - Processed Excel data output

How Do You Filter and Search Cells Across a Worksheet?

Beyond range-based access, IronXL lets you search for cells by value, apply conditional logic, and iterate rows and columns programmatically:

WorkBook workbook = WorkBook.Load("products.xlsx");
WorkSheet sheet = workbook.DefaultWorkSheet;

// Get total row and column counts
int rowCount = sheet.RowCount;
int colCount = sheet.ColumnCount;

Console.WriteLine($"Sheet dimensions: {rowCount} rows x {colCount} columns");

// Iterate over all rows and columns
for (int row = 1; row <= rowCount; row++)
{
    for (int col = 1; col <= colCount; col++)
    {
        var cell = sheet.GetCellAt(row, col);
        if (cell != null && !string.IsNullOrEmpty(cell.Text))
        {
            Console.WriteLine($"[{row},{col}] = {cell.Text}");
        }
    }
}

// Find the first cell containing specific text
var searchResult = sheet["A1:Z100"]
    .FirstOrDefault(c => c.StringValue.Contains("discontinued", StringComparison.OrdinalIgnoreCase));

if (searchResult != null)
{
    Console.WriteLine($"Found 'discontinued' at: {searchResult.AddressString}");
}
WorkBook workbook = WorkBook.Load("products.xlsx");
WorkSheet sheet = workbook.DefaultWorkSheet;

// Get total row and column counts
int rowCount = sheet.RowCount;
int colCount = sheet.ColumnCount;

Console.WriteLine($"Sheet dimensions: {rowCount} rows x {colCount} columns");

// Iterate over all rows and columns
for (int row = 1; row <= rowCount; row++)
{
    for (int col = 1; col <= colCount; col++)
    {
        var cell = sheet.GetCellAt(row, col);
        if (cell != null && !string.IsNullOrEmpty(cell.Text))
        {
            Console.WriteLine($"[{row},{col}] = {cell.Text}");
        }
    }
}

// Find the first cell containing specific text
var searchResult = sheet["A1:Z100"]
    .FirstOrDefault(c => c.StringValue.Contains("discontinued", StringComparison.OrdinalIgnoreCase));

if (searchResult != null)
{
    Console.WriteLine($"Found 'discontinued' at: {searchResult.AddressString}");
}
$vbLabelText   $csharpLabel

This pattern is common in data validation workflows where you need to scan an uploaded file for specific values before processing it further. For advanced filtering use cases, review the Excel range selection documentation.

What Deployment Scenarios Does This Approach Support?

One of the most practical advantages of using IronXL is its ability to operate without Microsoft Office installed anywhere on the system. This creates deployment flexibility that Interop-based solutions simply cannot match:

Cloud and Container Deployment

IronXL runs on Azure App Service, AWS Lambda, and Google Cloud Run without any special configuration. Because it carries no Office dependency, you avoid both the licensing cost and the complexity of including Office in a container image. A minimal Dockerfile for a .NET 10 app using IronXL needs only the standard .NET runtime image.

Docker-based deployment is equally straightforward. The IronXL Docker guide covers Debian, Alpine, and Windows container configurations. In all cases, you install IronXL via NuGet and it runs without additional system packages.

Server and CI/CD Pipeline Usage

Server environments often lack a GUI and cannot run applications that depend on a Windows desktop session. IronXL runs entirely in headless mode, making it suitable for:

  • Generating Excel reports in scheduled background jobs
  • Processing uploaded spreadsheets in ASP.NET Core APIs
  • Exporting DataTable or database query results to XLSX in automated pipelines
  • Validating imported data files during CI/CD test runs

For ASP.NET Core specifically, see the ASP.NET Core Excel export tutorial, which covers file streaming, response headers, and proper disposal patterns.

Cross-Platform Development

IronXL targets .NET Standard 2.0 and runs natively on Linux and macOS, enabling cross-platform development workflows. Developers on macOS can write and test Excel generation code locally with full confidence that the same binary will work identically on a Linux production server. There are no platform-specific APIs or conditional compilation blocks required.

For more details on supported environments, visit the IronXL getting started overview.

How Do You Handle Common Excel Operations Beyond Basic Reading?

Reading and writing cells is just the foundation. Real-world Excel automation typically involves formatting, formulas, worksheet management, and format conversion.

Formatting Cells and Applying Styles

IronXL exposes a complete style API covering fonts, colors, borders, alignment, and number formats:

WorkBook workbook = WorkBook.Load("report.xlsx");
WorkSheet sheet = workbook.DefaultWorkSheet;

// Apply bold, font size, and background color to header row
var headerRange = sheet["A1:F1"];
headerRange.Style.Font.Bold = true;
headerRange.Style.Font.Height = 12;
headerRange.Style.SetBackgroundColor("#4472C4");
headerRange.Style.Font.Color = "#FFFFFF";
headerRange.Style.HorizontalAlignment = IronXL.Styles.HorizontalAlignment.Center;

// Format a currency column
sheet["D2:D100"].FormatString = "$#,##0.00";

// Apply a date format
sheet["E2:E100"].FormatString = "yyyy-MM-dd";

// Add borders to a data range
var dataRange = sheet["A1:F20"];
dataRange.Style.Border.Bottom.Type = IronXL.Styles.BorderType.Thin;
dataRange.Style.Border.Right.Type = IronXL.Styles.BorderType.Thin;

workbook.SaveAs("formatted-report.xlsx");
WorkBook workbook = WorkBook.Load("report.xlsx");
WorkSheet sheet = workbook.DefaultWorkSheet;

// Apply bold, font size, and background color to header row
var headerRange = sheet["A1:F1"];
headerRange.Style.Font.Bold = true;
headerRange.Style.Font.Height = 12;
headerRange.Style.SetBackgroundColor("#4472C4");
headerRange.Style.Font.Color = "#FFFFFF";
headerRange.Style.HorizontalAlignment = IronXL.Styles.HorizontalAlignment.Center;

// Format a currency column
sheet["D2:D100"].FormatString = "$#,##0.00";

// Apply a date format
sheet["E2:E100"].FormatString = "yyyy-MM-dd";

// Add borders to a data range
var dataRange = sheet["A1:F20"];
dataRange.Style.Border.Bottom.Type = IronXL.Styles.BorderType.Thin;
dataRange.Style.Border.Right.Type = IronXL.Styles.BorderType.Thin;

workbook.SaveAs("formatted-report.xlsx");
$vbLabelText   $csharpLabel

For a full walkthrough of the styling options, see how to style cells, borders, and fonts.

Converting Between Excel and CSV Formats

IronXL handles format conversion directly, letting you load a CSV and save it as XLSX, or export an XLSX file to CSV for downstream processing:

// Load a CSV file and save as XLSX
WorkBook csvBook = WorkBook.Load("data-import.csv");
csvBook.SaveAs("data-import.xlsx");

// Load an XLSX file and export as CSV
WorkBook xlsxBook = WorkBook.Load("report.xlsx");
xlsxBook.DefaultWorkSheet.SaveAsCsv("report.csv");
// Load a CSV file and save as XLSX
WorkBook csvBook = WorkBook.Load("data-import.csv");
csvBook.SaveAs("data-import.xlsx");

// Load an XLSX file and export as CSV
WorkBook xlsxBook = WorkBook.Load("report.xlsx");
xlsxBook.DefaultWorkSheet.SaveAsCsv("report.csv");
$vbLabelText   $csharpLabel

For more detail on CSV handling, including delimiter configuration and encoding options, see the C# CSV reader tutorial and the CSV to XLSX conversion guide.

How Do You Get Started With a Free Trial?

IronXL is available for download with a free development license that lets you test the full feature set before committing to a purchase. There are no feature restrictions during the trial -- the same library that runs in production is the one you evaluate.

To get started:

  1. Install the package via NuGet:
    dotnet add package IronXL
    dotnet add package IronXL
    SHELL
  2. Visit the IronXL licensing page to obtain a free trial key.
  3. Apply the key in code before any IronXL calls:
    IronXL.License.LicenseKey = "YOUR-LICENSE-KEY-HERE";
    IronXL.License.LicenseKey = "YOUR-LICENSE-KEY-HERE";
    $vbLabelText   $csharpLabel

Licenses are available for individual developers, teams, and organizations. The IronXL product page provides full pricing details and deployment options, including royalty-free distribution rights. For a broader look at all Iron Software products and how they integrate, see the Iron Software product suite.

Frequently Asked Questions

How can I open Excel files in C# without Microsoft Office?

You can use IronXL to open Excel files in C# without the need for Microsoft Office. IronXL provides a modern alternative to Interop, offering better performance and no Excel dependencies.

What are the benefits of using IronXL for handling Excel files in C#?

IronXL offers several benefits, including improved performance, no dependency on Excel installations, and greater flexibility in deployment. It allows developers to automate reports, read data imports, and generate spreadsheets efficiently.

Can IronXL handle Excel files for automation tasks?

Yes, IronXL is well-suited for automation tasks such as generating weekly reports, reading data imports, and creating tools for dynamic spreadsheet generation.

Is IronXL a suitable replacement for Interop in C# applications?

IronXL is a suitable replacement for Interop, offering a modern solution that eliminates the need for Excel dependencies and improves application performance when working with Excel files.

Does IronXL support reading and writing to Excel files?

IronXL fully supports both reading from and writing to Excel files, making it a versatile tool for .NET developers handling spreadsheet data.

Jordi Bardia
Software Engineer
Jordi is most proficient in Python, C# and C++, when he isn’t leveraging his skills at Iron Software; he’s game programming. Sharing responsibilities for product testing, product development and research, Jordi adds immense value to continual product improvement. The varied experience keeps him challenged and engaged, and he ...
Read More

Iron Support Team

We're online 24 hours, 5 days a week.
Chat
Email
Call Me