Skip to footer content
USING IRONXL

How to Import Excel File in C#

Import Excel files in C# using IronXL, a .NET library that reads XLS, XLSX, CSV files without Microsoft Excel installed. Simply use WorkBook.Load("file.xlsx") to open files and access cell data with intuitive syntax like sheet["A1"].

Microsoft Excel is a versatile spreadsheet software that helps with data organization, presentation, and analysis. However, working with Excel programmatically in C# can be challenging, especially when dealing with different spreadsheet file types or when Microsoft Office isn't installed on your deployment server. The IronXL software library provides a comprehensive solution to import and read Excel files in C# applications, supporting various formats including XLSX, XLS, and CSV files.

What Is IronXL and Why Should I Use It for Excel Import?

IronXL is a .NET Excel library that prioritizes ease of use, accuracy, and speed. It helps you import and read Excel documents, and create and edit Excel files efficiently with lightning-fast performance. Unlike traditional approaches that require Microsoft Office Interop, IronXL works independently without MS Office Interop dependencies. This means you get all the functionalities to read Excel files without Excel installed. This makes IronXL a powerful tool for developers to import and read Excel files in C# applications, whether you're building ASP.NET web applications, desktop applications, or cloud-based solutions.

IronXL is available on all platforms like Windows, Linux, macOS, Docker, Azure, and AWS. It's compatible with all .NET Framework versions and supports modern .NET Core and .NET 5+ environments. IronXL is a versatile library that can be integrated into Console, Desktop, and Web ASP.NET applications, as well as Blazor applications. It supports different workbook formats like XLS and XLSX files, XSLT and XLSM, CSV, and TSV, making it ideal for scenarios where you need to convert between spreadsheet file types.

What Key Features Make IronXL Essential for Excel Import?

How Do I Import Excel Workbook in C#?

What Do I Need Before Starting Excel Import?

To use IronXL in C# to read Excel files, make sure the following components are installed on your computer:

  1. Visual Studio - This is the official IDE for developing C# .NET applications. Visual Studio provides excellent IntelliSense support and debugging tools that make working with Excel files easier. You can download and install Visual Studio from the Microsoft website. The Community Edition is free and sufficient for most development needs.

  2. IronXL - This is the library that helps you work with Excel sheets at a given path in C#. It must be installed in your C# program before using it. IronXL can be easily downloaded from the NuGet website or installed directly through the Manage NuGet packages interface in Visual Studio tools. You can also download the .NET Excel DLL file directly if you prefer manual installation.

For production deployments, you'll need to apply a license key to remove watermarks and enable full functionality. Development and testing can be done with the trial version.

Which Namespaces Should I Add to My Code?

Once Visual Studio and IronXL are installed, reference the IronXL assembly to use IronXL in your source code. Add the following line of code at the top of the file within the new project where IronXL functions will be used:

using IronXL;
using IronXL;
$vbLabelText   $csharpLabel

This single namespace import provides access to all the core functionality needed for Excel operations. If you're working with specific Excel features like charts or conditional formatting, you may need to import additional namespaces from the IronXL library.

How Do I Load and Open an Excel File?

Microsoft Excel Spreadsheets are also referred to as Excel Workbooks. Each workbook contains multiple worksheets (also called sheets), and a single worksheet contains tabular cells organized in rows and columns with their respective values. To open and read an Excel file, load it using the WorkBook class and Load method present in the IronXL library. The code goes as follows:

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

// You can also load from a stream
using (var stream = File.OpenRead("test.xlsx"))
{
    WorkBook streamWorkbook = WorkBook.Load(stream);
}

// Or load CSV files with custom delimiters
WorkBook csvWorkbook = WorkBook.LoadCSV("data.csv", delimiter: ",");
// Supported Excel spreadsheet formats for reading include: XLSX, XLS, CSV, and TSV
WorkBook workbook = WorkBook.Load("test.xlsx");

// You can also load from a stream
using (var stream = File.OpenRead("test.xlsx"))
{
    WorkBook streamWorkbook = WorkBook.Load(stream);
}

// Or load CSV files with custom delimiters
WorkBook csvWorkbook = WorkBook.LoadCSV("data.csv", delimiter: ",");
$vbLabelText   $csharpLabel

This opens the Excel file in the workbook instance reference variable. Since a workbook can have multiple worksheets, you can access them in various ways. The following code opens the first worksheet in the sheet instance variable:

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

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

// Or by index (zero-based)
WorkSheet indexedSheet = workbook.WorkSheets[0];
// Get the first worksheet
WorkSheet sheet = workbook.WorkSheets.First();

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

// Or by index (zero-based)
WorkSheet indexedSheet = workbook.WorkSheets[0];
$vbLabelText   $csharpLabel

This will open the first sheet in the Excel file, and now Excel data can be read from and written to this sheet. For more advanced scenarios, you might need to manage multiple worksheets or create new spreadsheets programmatically.

Opened Excel File

Excel spreadsheet showing employee data with columns for Name, Designation, and Salary, containing 5 employee records with various job titles and salaries Sample Excel file containing employee information that will be imported using C#. The data includes names, job designations (Manager, Director, Employee, President), and corresponding salary values.

How Can I Read Specific Cell Values After Import?

Once the Excel file is imported, it's ready for reading data. Reading Excel file data in C# using IronXL is very simple and easy. You can read Excel cell values by simply mentioning the cell reference number in standard Excel notation (like "A1", "B2", etc.). The library provides multiple ways to access cell values depending on the expected data type.

The code below retrieves the value of a cell with reference number "C2":

// Select cells easily in Excel-notation and return the value
int cellValue = sheet["C2"].IntValue;

// Display the value
Console.WriteLine(cellValue);

// You can also access different data types
string textValue = sheet["A2"].StringValue;
decimal decimalValue = sheet["C2"].DecimalValue;
double doubleValue = sheet["C2"].DoubleValue;
DateTime dateValue = sheet["D2"].DateTimeValue;
bool boolValue = sheet["E2"].BoolValue;

// Check if cell is empty
bool isEmpty = sheet["F2"].IsEmpty;
// Select cells easily in Excel-notation and return the value
int cellValue = sheet["C2"].IntValue;

// Display the value
Console.WriteLine(cellValue);

// You can also access different data types
string textValue = sheet["A2"].StringValue;
decimal decimalValue = sheet["C2"].DecimalValue;
double doubleValue = sheet["C2"].DoubleValue;
DateTime dateValue = sheet["D2"].DateTimeValue;
bool boolValue = sheet["E2"].BoolValue;

// Check if cell is empty
bool isEmpty = sheet["F2"].IsEmpty;
$vbLabelText   $csharpLabel

The output is as follows:

Microsoft Visual Studio Debug Console window showing the output of an Excel file reading operation, displaying the file path and a completion message The debug console output after successfully reading an Excel file in C#. The program has completed execution and is waiting for user input to close.

Now, let's read data from a range of cells in the opened Excel file. IronXL makes it easy to work with cell ranges using familiar Excel notation. The code goes as follows:

// Read from a range of cells elegantly.
foreach (var cell in sheet["A2:A6"])
{
    Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text);
}

// You can also work with entire rows or columns
var row = sheet.GetRow(2); // Get row 3 (0-indexed)
foreach (var cell in row)
{
    Console.WriteLine($"Row cell value: {cell.Value}");
}

// Or get a column
var column = sheet.GetColumn(0); // Get column A
foreach (var cell in column)
{
    Console.WriteLine($"Column A value: {cell.Value}");
}
// Read from a range of cells elegantly.
foreach (var cell in sheet["A2:A6"])
{
    Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text);
}

// You can also work with entire rows or columns
var row = sheet.GetRow(2); // Get row 3 (0-indexed)
foreach (var cell in row)
{
    Console.WriteLine($"Row cell value: {cell.Value}");
}

// Or get a column
var column = sheet.GetColumn(0); // Get column A
foreach (var cell in column)
{
    Console.WriteLine($"Column A value: {cell.Value}");
}
$vbLabelText   $csharpLabel

The code is very simple, clean, and clear. The range of cells can be referenced with simple syntax as shown in a foreach loop: sheet["A2:A6"] and each cell can be iterated to get its value. Here, you'll see the names in column A from row 2 to row 6 on the console output:

Microsoft Visual Studio Debug Console showing output from reading Excel cells A2 through A6, displaying names: John, Sara, Peter, Mathew, and Katherine Console output demonstrating successful reading of a range of Excel cells (A2:A6) containing names using C#

For more details on reading and writing to cell values, check out this tutorial on reading Excel files in C# example. You can also explore advanced features like applying formulas or working with named ranges.

How Do I Import Entire Worksheets at Once?

IronXL can be used to read Excel sheets at once using Rows and Columns indexes. This is particularly useful when you need to process all data in a worksheet or when you're converting Excel to other formats like CSV or JSON. The following IronXL code samples help you get the entire Excel file data in the same format on the console output:

WorkBook workbook = WorkBook.Load("test.xlsx");
WorkSheet sheet = workbook.WorkSheets.First();

// Traverse all rows of Excel WorkSheet
for (int i = 0; i < sheet.Rows.Count(); i++)
{
    // Traverse all columns of specific Row
    for (int j = 0; j < sheet.Columns.Count(); j++)
    {
        // Get the values
        string val = sheet.Rows[i].Columns[j].Value.ToString();
        Console.Write("{0}\t", val);
    }
    Console.WriteLine();
}

// Alternative method using LINQ for more efficient processing
var allData = sheet.Rows.SelectMany(row => 
    row.Columns.Select(col => col.Value?.ToString() ?? "")).ToList();
WorkBook workbook = WorkBook.Load("test.xlsx");
WorkSheet sheet = workbook.WorkSheets.First();

// Traverse all rows of Excel WorkSheet
for (int i = 0; i < sheet.Rows.Count(); i++)
{
    // Traverse all columns of specific Row
    for (int j = 0; j < sheet.Columns.Count(); j++)
    {
        // Get the values
        string val = sheet.Rows[i].Columns[j].Value.ToString();
        Console.Write("{0}\t", val);
    }
    Console.WriteLine();
}

// Alternative method using LINQ for more efficient processing
var allData = sheet.Rows.SelectMany(row => 
    row.Columns.Select(col => col.Value?.ToString() ?? "")).ToList();
$vbLabelText   $csharpLabel

For larger Excel files, you might want to consider using DataTable or DataSet objects for better performance and easier data manipulation:

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

// Process data using DataTable methods
foreach (DataRow row in dataTable.Rows)
{
    foreach (var item in row.ItemArray)
    {
        Console.Write($"{item}\t");
    }
    Console.WriteLine();
}
// Convert worksheet to DataTable for easier manipulation
DataTable dataTable = sheet.ToDataTable(true); // true = first row contains headers

// Process data using DataTable methods
foreach (DataRow row in dataTable.Rows)
{
    foreach (var item in row.ItemArray)
    {
        Console.Write($"{item}\t");
    }
    Console.WriteLine();
}
$vbLabelText   $csharpLabel

Output File

Microsoft Visual Studio Debug Console displaying employee data table with columns for Name, Designation, and Salary, showing 5 employee records read from an Excel file The console output successfully displays the employee data imported from the Excel file, with proper formatting showing names, job titles, and salary information.

.

What Are the Next Steps After Importing Excel Files?

This article demonstrated how to import and read an Excel file in C# without Microsoft Excel installed. It covered multiple ways to read data from an Excel spreadsheet, from individual cells to entire worksheets. IronXL also helps you create Excel files in C# without any Excel installation required.

After successfully importing Excel data, you might want to explore additional features:

IronXL provides an all-in-one solution for all Microsoft Excel document-related tasks to be implemented programmatically. You can perform formula calculations, string or number sorting, trimming and appending, find and replace, merge and unmerge cells, save files, and much more. You can edit cell values and also set cell data formats along with validating spreadsheet data. It also supports CSV files and helps you work with Excel data seamlessly.

For enterprise applications, consider exploring deployment options for various platforms including Docker containers, Azure Functions, and AWS Lambda.

IronXL is available for a free trial and can be licensed for commercial use with its Lite package starting from $799 only. The library offers excellent documentation, tutorials, and code examples to help you get started quickly with Excel file operations in your C# applications.

Frequently Asked Questions

How can I import and read an Excel file in C# without using Interop?

You can import and read Excel files in C# using the IronXL library. Simply load the Excel file using WorkBook.Load("file.xlsx") to access and process the data without needing Microsoft Excel installed.

What platforms is the IronXL library compatible with?

IronXL is compatible with all .NET Frameworks and can be used on multiple platforms including Windows, Linux, MacOS, Docker, Azure, and AWS.

Can I use IronXL to edit Excel files without having Microsoft Excel installed?

Yes, IronXL allows you to create and edit Excel files programmatically in C# without requiring Microsoft Excel to be installed on your system.

What Excel formats can IronXL handle?

IronXL supports various Excel file formats such as XLS, XLSX, CSV, TSV, and many more, allowing easy import and manipulation of data.

What are the prerequisites for using IronXL in a C# project?

To use IronXL, ensure you have Visual Studio installed. You can add IronXL to your project via the NuGet package manager or by downloading and referencing the .NET Excel DLL.

How can I load an Excel workbook with IronXL in C#?

To load an Excel workbook in C#, use IronXL's WorkBook.Load("path/to/file.xlsx") method, which allows you to open and manipulate the workbook.

Is it possible to handle Excel formulas using IronXL?

Yes, IronXL can process and recalculate Excel formulas seamlessly whenever a sheet is edited, ensuring accuracy in data calculations.

How do I read data from a specific cell using IronXL?

To read data from a specific cell, use IronXL syntax like sheet["B2"].StringValue to get the value from cell B2.

Can I iterate over a range of cells in an Excel sheet using IronXL?

Yes, you can iterate over a range of cells using IronXL with a syntax such as foreach (var cell in sheet["A1:C3"]) to process each cell individually.

How can IronXL be integrated into ASP.NET applications?

IronXL can be easily integrated into ASP.NET applications by adding the library via NuGet and referencing it in your project, enabling Excel file manipulation in web applications.

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