How to Import Excel Files in C#

As developers, we often need to import data from Excel files and use it to fulfill our application and data management requirements. Without requiring many lines of code, IronXL gives us an easy way to import exactly the data we need directly into a C# project and then manipulate it programmatically.


Step 1

1. Import Data with the IronXL Library

Import data using the functions provided by the IronXL Excel library, which we'll be using in this tutorial. The software is available free for development.

Install into your C# Project via DLL Download or navigate using the NuGet package.

Install-Package IronXL.Excel

How to Tutorial

2. Access WorkSheet for Project

For our project needs today, we will be importing Excel data into our C# application, using the IronXL software installed in step 1.

For step 2, we will load our Excel WorkBook in our CSharp project by using the WorkBook.Load() function of IronXL. We pass the path of the Excel WorkBook as a string parameter in this function, like this:

// Load Excel file
WorkBook wb = WorkBook.Load("Path");
// Load Excel file
WorkBook wb = WorkBook.Load("Path");
' Load Excel file
Dim wb As WorkBook = WorkBook.Load("Path")
$vbLabelText   $csharpLabel

The Excel file at the specified path will be loaded into wb.

Next, we need to access a specific WorkSheet of the Excel file whose data will be imported into the project. For this purpose, we can use the GetWorkSheet() function of IronXL, passing the sheet name as a string parameter to specify which sheet of the WorkBook to import.

// Specify sheet name of Excel WorkBook
WorkSheet ws = wb.GetWorkSheet("SheetName");
// Specify sheet name of Excel WorkBook
WorkSheet ws = wb.GetWorkSheet("SheetName");
' Specify sheet name of Excel WorkBook
Dim ws As WorkSheet = wb.GetWorkSheet("SheetName")
$vbLabelText   $csharpLabel

The WorkSheet will be imported as ws, and wb is the WorkBook which we have defined in the above code sample.

There are also the following alternative ways to import an Excel WorkSheet into the project.

// Import WorkSheet by various methods

// by sheet indexing
WorkSheet mySheet = wb.WorkSheets[SheetIndex];

// get default WorkSheet
WorkSheet defaultSheet = wb.DefaultWorkSheet;

// get first WorkSheet
WorkSheet firstSheet = wb.WorkSheets.First();

// for the first or default sheet
WorkSheet firstOrDefaultSheet = wb.WorkSheets.FirstOrDefault();
// Import WorkSheet by various methods

// by sheet indexing
WorkSheet mySheet = wb.WorkSheets[SheetIndex];

// get default WorkSheet
WorkSheet defaultSheet = wb.DefaultWorkSheet;

// get first WorkSheet
WorkSheet firstSheet = wb.WorkSheets.First();

// for the first or default sheet
WorkSheet firstOrDefaultSheet = wb.WorkSheets.FirstOrDefault();
' Import WorkSheet by various methods

' by sheet indexing
Dim mySheet As WorkSheet = wb.WorkSheets(SheetIndex)

' get default WorkSheet
Dim defaultSheet As WorkSheet = wb.DefaultWorkSheet

' get first WorkSheet
Dim firstSheet As WorkSheet = wb.WorkSheets.First()

' for the first or default sheet
Dim firstOrDefaultSheet As WorkSheet = wb.WorkSheets.FirstOrDefault()
$vbLabelText   $csharpLabel

Now, we can easily import any type of data from the specified Excel files. Let's see all the possible aspects which we use to import Excel file data in our project.


3. Import Excel Data in C#

This is the basic aspect of importing Excel file data into our project.

For this purpose, we can use a cell addressing system to specify which cell data we need to import. It will return the value of a specific cell address from the Excel file.

var cellValue = ws["Cell Address"];
var cellValue = ws["Cell Address"];
Dim cellValue = ws("Cell Address")
$vbLabelText   $csharpLabel

We can also import cell data from Excel files by using row and column indexes. This line of code will return the value of the specified row and column index.

var cellValueByIndex = ws.Rows[RowIndex].Columns[ColumnIndex];
var cellValueByIndex = ws.Rows[RowIndex].Columns[ColumnIndex];
Dim cellValueByIndex = ws.Rows(RowIndex).Columns(ColumnIndex)
$vbLabelText   $csharpLabel

If we want to assign imported cell values to variables, we can use this code.

// Import Data by Cell Address
// by cell addressing
string val = ws["Cell Address"].ToString();

// by row and column indexing
string valWithIndexing = ws.Rows[RowIndex].Columns[ColumnIndex].Value.ToString();
// Import Data by Cell Address
// by cell addressing
string val = ws["Cell Address"].ToString();

// by row and column indexing
string valWithIndexing = ws.Rows[RowIndex].Columns[ColumnIndex].Value.ToString();
' Import Data by Cell Address
' by cell addressing
Dim val As String = ws("Cell Address").ToString()

' by row and column indexing
Dim valWithIndexing As String = ws.Rows(RowIndex).Columns(ColumnIndex).Value.ToString()
$vbLabelText   $csharpLabel

In the above examples, the row and column index starts at 0.


4. Import Excel Data of Specific Range

If we want to import data in a specific range from an Excel WorkBook, it can easily be done by using the range function. To define the range, we need to describe the starting and ending cell addresses. This way, it will return all the cell values within the specified range.

var rangeData = ws["Starting Cell Address:Ending Cell Address"];
var rangeData = ws["Starting Cell Address:Ending Cell Address"];
Dim rangeData = ws("Starting Cell Address:Ending Cell Address")
$vbLabelText   $csharpLabel

For more information about working with range in Excel files, check out the provided code examples.

using IronXL;

static void Main(string[] args)
{
    // Import Excel WorkBook
    WorkBook wb = WorkBook.Load("sample.xlsx");

    // Specify WorkSheet
    WorkSheet ws = wb.GetWorkSheet("Sheet1");

    // Import data of specific cell
    string val = ws["A4"].Value.ToString();
    Console.WriteLine("Import Value of A4 Cell address: {0}", val);

    Console.WriteLine("import Values in Range From B3 To B9 :\n");

    // Import data in specific range
    foreach (var item in ws["B3:B9"])
    {
        Console.WriteLine(item.Value.ToString());
    }

    Console.ReadKey();
}
using IronXL;

static void Main(string[] args)
{
    // Import Excel WorkBook
    WorkBook wb = WorkBook.Load("sample.xlsx");

    // Specify WorkSheet
    WorkSheet ws = wb.GetWorkSheet("Sheet1");

    // Import data of specific cell
    string val = ws["A4"].Value.ToString();
    Console.WriteLine("Import Value of A4 Cell address: {0}", val);

    Console.WriteLine("import Values in Range From B3 To B9 :\n");

    // Import data in specific range
    foreach (var item in ws["B3:B9"])
    {
        Console.WriteLine(item.Value.ToString());
    }

    Console.ReadKey();
}
Imports Microsoft.VisualBasic
Imports IronXL

Shared Sub Main(ByVal args() As String)
	' Import Excel WorkBook
	Dim wb As WorkBook = WorkBook.Load("sample.xlsx")

	' Specify WorkSheet
	Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")

	' Import data of specific cell
	Dim val As String = ws("A4").Value.ToString()
	Console.WriteLine("Import Value of A4 Cell address: {0}", val)

	Console.WriteLine("import Values in Range From B3 To B9 :" & vbLf)

	' Import data in specific range
	For Each item In ws("B3:B9")
		Console.WriteLine(item.Value.ToString())
	Next item

	Console.ReadKey()
End Sub
$vbLabelText   $csharpLabel

The above code displays the following output:

1output related to 4. Import Excel Data of Specific Range

With the values of Excel file sample.xlsx as:

1excel related to 4. Import Excel Data of Specific Range

5. Import Excel Data by Aggregate Functions

We can also apply aggregate functions to Excel files and import the resulting data from these aggregate functions. Here are some examples of the different functions and how to use them.

  • Sum()

    // To find the sum of a specific cell range
    var sum = ws["Starting Cell Address:Ending Cell Address"].Sum();
    // To find the sum of a specific cell range
    var sum = ws["Starting Cell Address:Ending Cell Address"].Sum();
    ' To find the sum of a specific cell range
    Dim sum = ws("Starting Cell Address:Ending Cell Address").Sum()
    $vbLabelText   $csharpLabel
  • Average()

    // To find the average of a specific cell range
    var average = ws["Starting Cell Address:Ending Cell Address"].Avg();
    // To find the average of a specific cell range
    var average = ws["Starting Cell Address:Ending Cell Address"].Avg();
    ' To find the average of a specific cell range
    Dim average = ws("Starting Cell Address:Ending Cell Address").Avg()
    $vbLabelText   $csharpLabel
  • Min()

    // To find the minimum in a specific cell range
    var minimum = ws["Starting Cell Address:Ending Cell Address"].Min();
    // To find the minimum in a specific cell range
    var minimum = ws["Starting Cell Address:Ending Cell Address"].Min();
    ' To find the minimum in a specific cell range
    Dim minimum = ws("Starting Cell Address:Ending Cell Address").Min()
    $vbLabelText   $csharpLabel
  • Max()

    // To find the maximum in a specific cell range
    var maximum = ws["Starting Cell Address:Ending Cell Address"].Max();
    // To find the maximum in a specific cell range
    var maximum = ws["Starting Cell Address:Ending Cell Address"].Max();
    ' To find the maximum in a specific cell range
    Dim maximum = ws("Starting Cell Address:Ending Cell Address").Max()
    $vbLabelText   $csharpLabel

You can read more about working with aggregate functions in Excel for C# and learn more about pulling data in different methods.

Let's see an example of how to import Excel file data by applying these functions.

using IronXL;

static void Main(string[] args)
{
    // Import Excel file
    WorkBook wb = WorkBook.Load("sample.xlsx");

    // Specify WorkSheet
    WorkSheet ws = wb.GetWorkSheet("Sheet1");

    // Import Excel file data by applying aggregate functions
    decimal sum = ws["D2:D9"].Sum();
    decimal avg = ws["D2:D9"].Avg();
    decimal min = ws["D2:D9"].Min();
    decimal max = ws["D2:D9"].Max();

    Console.WriteLine("Sum From D2 To D9: {0}", sum);
    Console.WriteLine("Avg From D2 To D9: {0}", avg);
    Console.WriteLine("Min From D2 To D9: {0}", min);
    Console.WriteLine("Max From D2 To D9: {0}", max);

    Console.ReadKey();
}
using IronXL;

static void Main(string[] args)
{
    // Import Excel file
    WorkBook wb = WorkBook.Load("sample.xlsx");

    // Specify WorkSheet
    WorkSheet ws = wb.GetWorkSheet("Sheet1");

    // Import Excel file data by applying aggregate functions
    decimal sum = ws["D2:D9"].Sum();
    decimal avg = ws["D2:D9"].Avg();
    decimal min = ws["D2:D9"].Min();
    decimal max = ws["D2:D9"].Max();

    Console.WriteLine("Sum From D2 To D9: {0}", sum);
    Console.WriteLine("Avg From D2 To D9: {0}", avg);
    Console.WriteLine("Min From D2 To D9: {0}", min);
    Console.WriteLine("Max From D2 To D9: {0}", max);

    Console.ReadKey();
}
Imports IronXL

Shared Sub Main(ByVal args() As String)
	' Import Excel file
	Dim wb As WorkBook = WorkBook.Load("sample.xlsx")

	' Specify WorkSheet
	Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")

	' Import Excel file data by applying aggregate functions
	Dim sum As Decimal = ws("D2:D9").Sum()
	Dim avg As Decimal = ws("D2:D9").Avg()
	Dim min As Decimal = ws("D2:D9").Min()
	Dim max As Decimal = ws("D2:D9").Max()

	Console.WriteLine("Sum From D2 To D9: {0}", sum)
	Console.WriteLine("Avg From D2 To D9: {0}", avg)
	Console.WriteLine("Min From D2 To D9: {0}", min)
	Console.WriteLine("Max From D2 To D9: {0}", max)

	Console.ReadKey()
End Sub
$vbLabelText   $csharpLabel

The above code gives us this output:

2output related to 5. Import Excel Data by Aggregate Functions

And our file sample.xlsx will have these values:

2excel related to 5. Import Excel Data by Aggregate Functions

6. Import Complete Excel File Data

If we want to import complete Excel file data into our C# project, we can first parse our loaded WorkBook into a DataSet. In this way, the complete Excel data would be imported into the DataSet, and WorkSheets on Excel files become DataTables within that DataSet. Here it is in action:

// Import WorkBook into DataSet
DataSet ds = wb.ToDataSet();
// Import WorkBook into DataSet
DataSet ds = wb.ToDataSet();
' Import WorkBook into DataSet
Dim ds As DataSet = wb.ToDataSet()
$vbLabelText   $csharpLabel

In this way, our specified WorkSheet will be imported into a DataSet that we can use according to our requirements.

Often, the first column of an Excel file is used as ColumnName. In this case, we need to make the first column a DataTable ColumnName. To do this, we set the boolean parameter of ToDataSet() function of IronXL as follows:

// Import WorkBook into DataSet with first row as ColumnNames
DataSet ds = wb.ToDataSet(true);
// Import WorkBook into DataSet with first row as ColumnNames
DataSet ds = wb.ToDataSet(true);
' Import WorkBook into DataSet with first row as ColumnNames
Dim ds As DataSet = wb.ToDataSet(True)
$vbLabelText   $csharpLabel

This will make the first column of the Excel file as a DataTable ColumnName.

Let's see a complete example of how to import Excel data into a DataSet and use the first column of an Excel WorkSheet as a DataTable ColumnName:

using IronXL;

static void Main(string[] args)
{
    WorkBook wb = WorkBook.Load("sample.xlsx");
    WorkSheet ws = wb.GetWorkSheet("Sheet1");

    // Import Excel data into a DataSet
    DataSet ds = wb.ToDataSet(true);

    Console.WriteLine("Excel file data imported to dataset successfully.");
    Console.ReadKey();
}
using IronXL;

static void Main(string[] args)
{
    WorkBook wb = WorkBook.Load("sample.xlsx");
    WorkSheet ws = wb.GetWorkSheet("Sheet1");

    // Import Excel data into a DataSet
    DataSet ds = wb.ToDataSet(true);

    Console.WriteLine("Excel file data imported to dataset successfully.");
    Console.ReadKey();
}
Imports IronXL

Shared Sub Main(ByVal args() As String)
	Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
	Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")

	' Import Excel data into a DataSet
	Dim ds As DataSet = wb.ToDataSet(True)

	Console.WriteLine("Excel file data imported to dataset successfully.")
	Console.ReadKey()
End Sub
$vbLabelText   $csharpLabel

Working with Excel Dataset and Datatable functions can be complicated, but we have more examples available for incorporating file data into your C# project.


Library Quick Access

Explore the IronXL Reference

Learn more about pulling Excel data via cells, range, datasets and datatables in our full documentation API Reference for IronXl.

Explore the IronXL Reference
Documentation related to Library Quick Access

Frequently Asked Questions

What is IronXL?

IronXL is a C# library that allows developers to import, manipulate, and export Excel data within a C# project without using Interop.

How do I install IronXL in my C# project?

You can install IronXL via NuGet by running the command 'Install-Package IronXL.Excel' in your Package Manager Console.

How can I import an Excel file in C# using IronXL?

You can import an Excel file by using the 'WorkBook.Load()' method and providing the path to your Excel file.

How do I access a specific worksheet in an Excel workbook using IronXL?

You can access a specific worksheet by using the 'GetWorkSheet()' method and passing the sheet name as a parameter.

Can IronXL import data from a specific range of cells?

Yes, IronXL can import data from a specific range of cells by specifying the starting and ending cell addresses using the range function.

What aggregate functions are supported by IronXL for importing data?

IronXL supports aggregate functions such as Sum, Average, Min, and Max for importing data from Excel files.

How can I import complete Excel file data into a C# project?

You can import complete Excel file data into a C# project by parsing the loaded WorkBook into a DataSet using the 'ToDataSet()' method.

Is it possible to use the first row of an Excel file as DataTable column names?

Yes, you can use the first row of an Excel file as DataTable column names by setting the boolean parameter of the 'ToDataSet()' function to true.

How can I learn more about using IronXL for Excel operations?

You can explore the full documentation API Reference for IronXL to learn more about pulling Excel data via cells, range, datasets, and datatables.

Chaknith Bin
Software Engineer
Chaknith works on IronXL and IronBarcode. He has deep expertise in C# and .NET, helping improve the software and support customers. His insights from user interactions contribute to better products, documentation, and overall experience.