Skip to footer content
USING IRONXL

How to Open Excel Files in C#

IronXL enables C# developers to open, read, and manipulate Excel files without requiring Microsoft Office installation. Simply load workbooks using WorkBook.Load(), access worksheets, and read cell values with intuitive syntax like sheet["A1"].

This tutorial explores using IronXL to open and read Excel files in C# projects, providing junior developers with comprehensive examples and best practices for working with Excel data.

What is IronXL Excel Library?

IronXL is a .NET library that prioritizes ease of use, accuracy, and speed. It helps you open, read, create, and edit Excel files efficiently without requiring MS Office Interop, making it a practical choice for developers seeking to work with Excel in C# without Interop.

IronXL is compatible with all .NET Frameworks along with Linux, macOS, Docker, Azure, and AWS. You can use it to create Console, Web, and Desktop Applications such as Blazor and .NET MAUI for modern Web Apps. It supports different workbook formats like XLS and XLSX files, XSLT and XLSM, CSV, and TSV.

What Are the Key Features of IronXL?

How to Open an Excel File in C#?

What Do I Need Before Starting?

To use IronXL in C# applications, install the following components on your local computer:

  1. Visual Studio - The official IDE for developing C# .NET applications. You can download and install Visual Studio from the Microsoft website. You can also use JetBrains ReSharper & Rider. For additional setup guidance, refer to the Get Started Overview.
  2. IronXL - The Excel library that helps work with Excel sheets in C#. It must be installed in your C# application before using it. You can download it from the NuGet website or from Manage NuGet packages in Visual Studio. You can also download the .NET Excel DLL file directly. For licensing implementation, see Using License Keys.

Which Namespaces Should I Import?

Once Visual Studio and IronXL are installed, add the necessary IronXL namespaces by including the following line at the top of your C# file:

// Add reference to the IronXL library
using IronXL;
// Add reference to the IronXL library
using IronXL;
' Add reference to the IronXL library
Imports IronXL
$vbLabelText   $csharpLabel

For working with specific Excel formats or advanced features, you might also need:

using IronXL.Formatting;  // For cell styling
using IronXL.Drawing;     // For images and charts
using System.Data;        // For DataSet/DataTable operations
using IronXL.Formatting;  // For cell styling
using IronXL.Drawing;     // For images and charts
using System.Data;        // For DataSet/DataTable operations
Imports IronXL.Formatting  ' For cell styling
Imports IronXL.Drawing     ' For images and charts
Imports System.Data        ' For DataSet/DataTable operations
$vbLabelText   $csharpLabel

How Do I Load an Existing Excel File?

Excel files, also known as workbooks, consist of multiple worksheets, each containing cell values. To open and read an Excel file, load it using the WorkBook class's Load method. The LoadSpreadsheets functionality supports various formats.

// Supported Excel spreadsheet formats for reading include: XLSX, XLS, CSV, and TSV
WorkBook workbook = WorkBook.Load("test.xlsx");

// You can also load from streams for web applications
// using (var stream = File.OpenRead("test.xlsx"))
// {
//     WorkBook workbook = WorkBook.Load(stream);
// }
// Supported Excel spreadsheet formats for reading include: XLSX, XLS, CSV, and TSV
WorkBook workbook = WorkBook.Load("test.xlsx");

// You can also load from streams for web applications
// using (var stream = File.OpenRead("test.xlsx"))
// {
//     WorkBook workbook = WorkBook.Load(stream);
// }
' Supported Excel spreadsheet formats for reading include: XLSX, XLS, CSV, and TSV
Dim workbook As WorkBook = WorkBook.Load("test.xlsx")

' You can also load from streams for web applications
' Using stream = File.OpenRead("test.xlsx")
'     Dim workbook As WorkBook = WorkBook.Load(stream)
' End Using
$vbLabelText   $csharpLabel

This initializes the workbook as a WorkBook instance. To open a specific WorkSheet, retrieve it from the WorkSheets collection. The Manage Worksheet guide provides more details on worksheet operations:

// Access the first worksheet in the workbook
WorkSheet sheet = workbook.WorkSheets.First();

// Alternative ways to access worksheets
WorkSheet sheetByIndex = workbook.WorkSheets[0];  // By index
WorkSheet sheetByName = workbook.GetWorkSheet("Sheet1");  // By name
// Access the first worksheet in the workbook
WorkSheet sheet = workbook.WorkSheets.First();

// Alternative ways to access worksheets
WorkSheet sheetByIndex = workbook.WorkSheets[0];  // By index
WorkSheet sheetByName = workbook.GetWorkSheet("Sheet1");  // By name
' Access the first worksheet in the workbook
Dim sheet As WorkSheet = workbook.WorkSheets.First()

' Alternative ways to access worksheets
Dim sheetByIndex As WorkSheet = workbook.WorkSheets(0)  ' By index
Dim sheetByName As WorkSheet = workbook.GetWorkSheet("Sheet1")  ' By name
$vbLabelText   $csharpLabel

This accesses the first sheet in the Excel file, ready for reading and writing.

Excel spreadsheet showing employee data with columns for Name, Designation, and Salary across 5 employees with formatted headers and cell borders Excel File

How Do I Read Data from Excel Cells?

Once the Excel file is opened, it's ready for reading data. Reading data from Excel files in C# using IronXL is straightforward. You can read cell values by specifying the cell reference using the Select Range functionality.

The following code retrieves the value of a cell:

// Select the cell using Excel notation and retrieve its integer value
int cellValue = sheet["C2"].IntValue;

// You can also retrieve values in different formats
string textValue = sheet["C2"].StringValue;
decimal decimalValue = sheet["C2"].DecimalValue;
DateTime dateValue = sheet["C2"].DateTimeValue;
bool boolValue = sheet["C2"].BoolValue;

// Display the value in the console
Console.WriteLine($"Cell C2 contains: {cellValue}");

// Check if cell is empty before reading
if (!sheet["C2"].IsEmpty)
{
    Console.WriteLine($"Cell value: {sheet["C2"].Value}");
}
// Select the cell using Excel notation and retrieve its integer value
int cellValue = sheet["C2"].IntValue;

// You can also retrieve values in different formats
string textValue = sheet["C2"].StringValue;
decimal decimalValue = sheet["C2"].DecimalValue;
DateTime dateValue = sheet["C2"].DateTimeValue;
bool boolValue = sheet["C2"].BoolValue;

// Display the value in the console
Console.WriteLine($"Cell C2 contains: {cellValue}");

// Check if cell is empty before reading
if (!sheet["C2"].IsEmpty)
{
    Console.WriteLine($"Cell value: {sheet["C2"].Value}");
}
' Select the cell using Excel notation and retrieve its integer value
Dim cellValue As Integer = sheet("C2").IntValue

' You can also retrieve values in different formats
Dim textValue As String = sheet("C2").StringValue
Dim decimalValue As Decimal = sheet("C2").DecimalValue
Dim dateValue As DateTime = sheet("C2").DateTimeValue
Dim boolValue As Boolean = sheet("C2").BoolValue

' Display the value in the console
Console.WriteLine($"Cell C2 contains: {cellValue}")

' Check if cell is empty before reading
If Not sheet("C2").IsEmpty Then
    Console.WriteLine($"Cell value: {sheet("C2").Value}")
End If
$vbLabelText   $csharpLabel

The output is as follows:

Microsoft Visual Studio Debug Console window showing successful extraction of value '100000' from Excel cell C2 with contextual output message Read Excel

To read data from a range of cells, use a loop to iterate through the specified range. The Select Excel Range example provides more patterns:

// Iterate through a range of cells and display their address and text content
foreach (var cell in sheet["A2:A6"])
{
    Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text);
}

// Read an entire column
foreach (var cell in sheet.GetColumn(0))  // Column A
{
    if (!cell.IsEmpty)
    {
        Console.WriteLine($"Column A value: {cell.Text}");
    }
}

// Read an entire row
foreach (var cell in sheet.GetRow(1))  // Row 2
{
    Console.WriteLine($"Row 2 value: {cell.Text}");
}
// Iterate through a range of cells and display their address and text content
foreach (var cell in sheet["A2:A6"])
{
    Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text);
}

// Read an entire column
foreach (var cell in sheet.GetColumn(0))  // Column A
{
    if (!cell.IsEmpty)
    {
        Console.WriteLine($"Column A value: {cell.Text}");
    }
}

// Read an entire row
foreach (var cell in sheet.GetRow(1))  // Row 2
{
    Console.WriteLine($"Row 2 value: {cell.Text}");
}
' Iterate through a range of cells and display their address and text content
For Each cell In sheet("A2:A6")
    Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text)
Next

' Read an entire column
For Each cell In sheet.GetColumn(0) ' Column A
    If Not cell.IsEmpty Then
        Console.WriteLine($"Column A value: {cell.Text}")
    End If
Next

' Read an entire row
For Each cell In sheet.GetRow(1) ' Row 2
    Console.WriteLine($"Row 2 value: {cell.Text}")
Next
$vbLabelText   $csharpLabel

Each value in the cell range A2:A6 is accessed and printed to the console.

Microsoft Visual Studio Debug Console with syntax highlighting showing output from reading Excel range A2:A6, displaying employee names John, Sara, Peter, Method, and Katherine Read Range of Cells

For more detailed reading and writing examples, check the Excel reading tutorial in C#. You can also convert Excel data to DataTables for easier manipulation:

// Convert worksheet to DataTable for easier data manipulation
DataTable dataTable = sheet.ToDataTable(true);  // true = first row contains headers

// Access data using DataTable methods
foreach (DataRow row in dataTable.Rows)
{
    Console.WriteLine($"Employee: {row["Name"]}, Salary: {row["Salary"]}");
}
// Convert worksheet to DataTable for easier data manipulation
DataTable dataTable = sheet.ToDataTable(true);  // true = first row contains headers

// Access data using DataTable methods
foreach (DataRow row in dataTable.Rows)
{
    Console.WriteLine($"Employee: {row["Name"]}, Salary: {row["Salary"]}");
}
' Convert worksheet to DataTable for easier data manipulation
Dim dataTable As DataTable = sheet.ToDataTable(True)  ' True = first row contains headers

' Access data using DataTable methods
For Each row As DataRow In dataTable.Rows
    Console.WriteLine($"Employee: {row("Name")}, Salary: {row("Salary")}")
Next
$vbLabelText   $csharpLabel

How Can I Create a New Excel File?

IronXL also facilitates creating new workbooks for data saving and retrieval. The Create Spreadsheets guide provides comprehensive examples.

You can create a new Excel file with a single line of code:

// Create a new workbook with the XLSX format
WorkBook workBook = new WorkBook(ExcelFileFormat.XLSX);

// Alternative: Create with XLS format for compatibility
WorkBook xlsWorkBook = new WorkBook(ExcelFileFormat.XLS);

// Set workbook metadata
workBook.Metadata.Title = "Employee Data";
workBook.Metadata.Author = "Your Name";
workBook.Metadata.Keywords = "employees, salary, data";
// Create a new workbook with the XLSX format
WorkBook workBook = new WorkBook(ExcelFileFormat.XLSX);

// Alternative: Create with XLS format for compatibility
WorkBook xlsWorkBook = new WorkBook(ExcelFileFormat.XLS);

// Set workbook metadata
workBook.Metadata.Title = "Employee Data";
workBook.Metadata.Author = "Your Name";
workBook.Metadata.Keywords = "employees, salary, data";
' Create a new workbook with the XLSX format
Dim workBook As New WorkBook(ExcelFileFormat.XLSX)

' Alternative: Create with XLS format for compatibility
Dim xlsWorkBook As New WorkBook(ExcelFileFormat.XLS)

' Set workbook metadata
workBook.Metadata.Title = "Employee Data"
workBook.Metadata.Author = "Your Name"
workBook.Metadata.Keywords = "employees, salary, data"
$vbLabelText   $csharpLabel

Next, create a worksheet and add data to it. For more advanced creation patterns, see Create a new Excel File.

How Do I Add Worksheets to a Workbook?

// Create a worksheet named "GDPByCountry" in the workbook
WorkSheet workSheet = workBook.CreateWorkSheet("GDPByCountry");

// Create multiple worksheets at once
WorkSheet sheet2 = workBook.CreateWorkSheet("PopulationData");
WorkSheet sheet3 = workBook.CreateWorkSheet("Summary");

// Copy an existing worksheet
WorkSheet copiedSheet = workSheet.CopySheet("GDPByCountryCopy");
// Create a worksheet named "GDPByCountry" in the workbook
WorkSheet workSheet = workBook.CreateWorkSheet("GDPByCountry");

// Create multiple worksheets at once
WorkSheet sheet2 = workBook.CreateWorkSheet("PopulationData");
WorkSheet sheet3 = workBook.CreateWorkSheet("Summary");

// Copy an existing worksheet
WorkSheet copiedSheet = workSheet.CopySheet("GDPByCountryCopy");
' Create a worksheet named "GDPByCountry" in the workbook
Dim workSheet As WorkSheet = workBook.CreateWorkSheet("GDPByCountry")

' Create multiple worksheets at once
Dim sheet2 As WorkSheet = workBook.CreateWorkSheet("PopulationData")
Dim sheet3 As WorkSheet = workBook.CreateWorkSheet("Summary")

' Copy an existing worksheet
Dim copiedSheet As WorkSheet = workSheet.CopySheet("GDPByCountryCopy")
$vbLabelText   $csharpLabel

This code adds a worksheet named "GDPByCountry" to the workbook, allowing you to add cell values. Learn more about managing worksheets and copying worksheets.

To set a value for a specific cell, use the code below:

// Set the value of cell A1 to "Example"
workSheet["A1"].Value = "Example";

// Add different types of data
workSheet["A2"].Value = 12345;  // Integer
workSheet["A3"].Value = 99.99m;  // Decimal
workSheet["A4"].Value = DateTime.Now;  // Date
workSheet["A5"].Value = true;  // Boolean

// Add formulas
workSheet["B1"].Formula = "=SUM(A2:A3)";

// Set multiple cells at once using a range
workSheet["C1:C5"].Value = "Bulk Value";

// Save the workbook
workBook.SaveAs("output.xlsx");
// Set the value of cell A1 to "Example"
workSheet["A1"].Value = "Example";

// Add different types of data
workSheet["A2"].Value = 12345;  // Integer
workSheet["A3"].Value = 99.99m;  // Decimal
workSheet["A4"].Value = DateTime.Now;  // Date
workSheet["A5"].Value = true;  // Boolean

// Add formulas
workSheet["B1"].Formula = "=SUM(A2:A3)";

// Set multiple cells at once using a range
workSheet["C1:C5"].Value = "Bulk Value";

// Save the workbook
workBook.SaveAs("output.xlsx");
' Set the value of cell A1 to "Example"
workSheet("A1").Value = "Example"

' Add different types of data
workSheet("A2").Value = 12345  ' Integer
workSheet("A3").Value = 99.99D  ' Decimal
workSheet("A4").Value = DateTime.Now  ' Date
workSheet("A5").Value = True  ' Boolean

' Add formulas
workSheet("B1").Formula = "=SUM(A2:A3)"

' Set multiple cells at once using a range
workSheet("C1:C5").Value = "Bulk Value"

' Save the workbook
workBook.SaveAs("output.xlsx")
$vbLabelText   $csharpLabel

The final output is:

Excel spreadsheet showing cell A1 populated with 'Example' text programmatically added using C#, with the GDPByCountry worksheet tab visible and cell highlighting to show the added value Add Value to Cell

Working with Different Excel Formats

IronXL supports multiple Excel formats. Here's how to handle different file types:

// Convert between formats
WorkBook workbook = WorkBook.Load("data.csv");
workbook.SaveAs("data.xlsx");  // Convert CSV to XLSX

// Export to different formats
workbook.SaveAsCsv("output.csv", ";");  // CSV with semicolon delimiter
workbook.SaveAsJson("output.json");     // Export as JSON
workbook.SaveAsXml("output.xml");       // Export as XML
// Convert between formats
WorkBook workbook = WorkBook.Load("data.csv");
workbook.SaveAs("data.xlsx");  // Convert CSV to XLSX

// Export to different formats
workbook.SaveAsCsv("output.csv", ";");  // CSV with semicolon delimiter
workbook.SaveAsJson("output.json");     // Export as JSON
workbook.SaveAsXml("output.xml");       // Export as XML
' Convert between formats
Dim workbook As WorkBook = WorkBook.Load("data.csv")
workbook.SaveAs("data.xlsx")  ' Convert CSV to XLSX

' Export to different formats
workbook.SaveAsCsv("output.csv", ";")  ' CSV with semicolon delimiter
workbook.SaveAsJson("output.json")     ' Export as JSON
workbook.SaveAsXml("output.xml")       ' Export as XML
$vbLabelText   $csharpLabel

Learn more about converting spreadsheet file types and converting XLSX to CSV, JSON, XML.

Error Handling and Best Practices

When working with Excel files, implement proper error handling:

try
{
    WorkBook workbook = WorkBook.Load("test.xlsx");
    WorkSheet sheet = workbook.GetWorkSheet("Sheet1");

    // Check if sheet exists
    if (sheet == null)
    {
        Console.WriteLine("Worksheet not found!");
        return;
    }

    // Process data
    var value = sheet["A1"].Value;
}
catch (Exception ex)
{
    Console.WriteLine($"Error reading Excel file: {ex.Message}");
}
try
{
    WorkBook workbook = WorkBook.Load("test.xlsx");
    WorkSheet sheet = workbook.GetWorkSheet("Sheet1");

    // Check if sheet exists
    if (sheet == null)
    {
        Console.WriteLine("Worksheet not found!");
        return;
    }

    // Process data
    var value = sheet["A1"].Value;
}
catch (Exception ex)
{
    Console.WriteLine($"Error reading Excel file: {ex.Message}");
}
Imports System

Try
    Dim workbook As WorkBook = WorkBook.Load("test.xlsx")
    Dim sheet As WorkSheet = workbook.GetWorkSheet("Sheet1")

    ' Check if sheet exists
    If sheet Is Nothing Then
        Console.WriteLine("Worksheet not found!")
        Return
    End If

    ' Process data
    Dim value = sheet("A1").Value
Catch ex As Exception
    Console.WriteLine($"Error reading Excel file: {ex.Message}")
End Try
$vbLabelText   $csharpLabel

For production applications, consider setting up logging and implementing proper error handling patterns.

What Have We Learned?

This article demonstrates how to open and read Excel files, such as XLS and XLSX, in C# using IronXL. IronXL doesn't require Microsoft Excel to be installed on the system for Excel-related tasks, making it perfect for Docker deployments and Azure functions.

IronXL provides a comprehensive solution for Excel-related tasks programmatically, including formula calculation, string sorting, trimming, finding and replacing, merging and unmerging, saving files, and more. You can also set cell data formats, work with conditional formatting, and create charts.

For advanced features, explore grouping and ungrouping, named ranges, hyperlinks, and protecting Excel files. The complete API Reference provides detailed documentation for all features.

IronXL is available for a free 30-day trial and can be licensed for commercial use. IronXL's Lite package starts from $799. For additional resources, visit the tutorials section or explore code examples for common scenarios.

Frequently Asked Questions

How can I open Excel files in C# without using Interop?

You can open Excel files in C# without using Interop by utilizing the IronXL library. Use the WorkBook.Load method to load an Excel file into a WorkBook instance, which allows you to access and manipulate data within the file.

What file formats are compatible with this C# Excel library?

IronXL supports a variety of Excel file formats including XLS, XLSX, CSV, and TSV. This allows developers to open, read, and write these formats flexibly within their C# applications.

Can I edit Excel files in C# using this library?

Yes, you can edit Excel files using IronXL. After loading a workbook, you can modify data, add new worksheets, and then save changes back to the file or export it in various formats.

How do I install this library for use in my C# project?

To install IronXL in your C# project, you can use NuGet Package Manager in Visual Studio to add the library. Alternatively, you can download the .NET Excel DLL and reference it in your project.

Is it possible to encrypt Excel files using this library?

Yes, IronXL allows you to encrypt and decrypt Excel files. You can secure your Excel documents with passwords to protect sensitive data during file operations.

Does this library support formula recalculations in Excel sheets?

IronXL supports automatic formula recalculations, ensuring that any changes to the data automatically update the formulas, just like in Excel.

How can I read specific cell values in an Excel worksheet using this library?

To read specific cell values using IronXL, you can reference the cell using Excel notation. For example, sheet["A1"].StringValue will retrieve the string value from cell A1.

Can this library be used across different operating systems?

Yes, IronXL is compatible with multiple operating systems, including Windows, Linux, and macOS. It also supports deployment in Docker, Azure, and AWS environments.

What are the advantages of using this library over MS Office Interop?

IronXL offers several advantages over MS Office Interop, such as not requiring Excel to be installed on the system, better performance in server environments, and ease of use with modern .NET applications.

Is there a free trial available for this C# Excel library?

Yes, IronXL provides a 30-day free trial, allowing you to test its features and capabilities before deciding on a commercial license for your projects.

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