跳至页脚内容
使用 IRONXL

如何在 C# 中导入 Excel 文件

Microsoft Excel is a versatile spreadsheet software that aids in data organization, presentation, and analysis. However, working with Excel programmatically in C# can be challenging. The IronXL software library can be used to import and read Excel files in C#.

IronXL - Excel Library

IronXL is a .NET Excel library that prioritizes ease of use, accuracy, and speed for its users. It helps you to import and read Excel documents, and create and edit an Excel file efficiently with lightning-fast performance. It works without MS Office Interop. This means without Excel installed, it provides all the functionalities to read Excel files. This makes IronXL a powerful tool for developers to import and read Excel files in C#.

IronXL is available on all platforms like Windows, Linux, MacOS, Docker, Azure, and AWS. It is compatible with all .NET Framework. IronXL is a versatile library that can be integrated into Console, Desktop, and Web ASP.NET applications. It supports different workbook formats like XLS and XLSX files, XSLT and XLSM, CSV, and TSV.

Some Important Features

  • Open, read Excel files and search data from different spreadsheet formats like XLS/CSV/TSV/XLSX files.
  • Exporting Excel Worksheets to XLS/XLSX/CSV/TSV/JSON.
  • Encrypting and decrypting XLSM/XLTX/XLSX files with passwords.
  • Import Excel sheet as System.Data.DataSet and System.Data.DataTable objects.
  • Excel file formulas are recalculated every time a sheet is edited.
  • Intuitive cell range settings with a WorkSheet["A1:B10"] easy syntax.
  • Sort Cell Ranges, Columns, and Rows.
  • Styling Cells - Font, Font Size, Background color, Border, Alignment, and Numbering formats.

How to Import Excel Workbook in C#?

Prerequisites

To use IronXL in C# to read Excel files, please ensure the following components are installed on the computer:

  1. Visual Studio - It is the official IDE for developing C# .NET applications. You can download and install Visual Studio from the Microsoft website.
  2. IronXL - It is the library that helps to work with Excel sheets at a given path in C#. It must be installed in a C# program before using it. IronXL can be downloaded from the NuGet website or Manage NuGet packages in Visual Studio tools. You can also download the .NET Excel DLL file directly.

Adding Necessary Namespaces

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

using IronXL;
using IronXL;
Imports IronXL
$vbLabelText   $csharpLabel

Open an Existing Excel file in C#

Microsoft Excel Spreadsheets are also referred to as Excel Workbooks. Each workbook contains multiple worksheets and a single worksheet contains tabular cells with its value. To open and read an Excel file, it should be loaded 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");
// Supported Excel spreadsheet formats for reading include: XLSX, XLS, CSV, and TSV
WorkBook workbook = WorkBook.Load("test.xlsx");
' Supported Excel spreadsheet formats for reading include: XLSX, XLS, CSV, and TSV
Dim workbook As WorkBook = WorkBook.Load("test.xlsx")
$vbLabelText   $csharpLabel

This opens the Excel file in the workbook instance reference variable. As it can have multiple worksheets, it can be used to open a specific worksheet or all at once. The following code opens the first worksheet in the sheet instance variable:

WorkSheet sheet = workbook.WorkSheets.First();
WorkSheet sheet = workbook.WorkSheets.First();
Dim sheet As WorkSheet = workbook.WorkSheets.First()
$vbLabelText   $csharpLabel

This will open the first sheet in the Excel file and now Excel data can be read and written to this sheet.

Opened Excel File

How to Import Excel File in C#, Figure 1: The Excel file The Excel file

Read Data from the Imported Excel File

Once the Excel file is imported, it is 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.

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);
// Select cells easily in Excel-notation and return the value
int cellValue = sheet["C2"].IntValue;

// Display the value
Console.WriteLine(cellValue);
' Select cells easily in Excel-notation and return the value
Dim cellValue As Integer = sheet("C2").IntValue

' Display the value
Console.WriteLine(cellValue)
$vbLabelText   $csharpLabel

The output is as follows:

How to Import Excel File in C#, Figure 2: Read Excel Read Excel

Now, let's read data from a range of cells in the opened Excel file. 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);
}
// 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);
}
' Read from a range of cells elegantly.
For Each cell In sheet("A2:A6")
	Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text)
Next cell
$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 will see the names in column A from row 2 to row 6 on the console output:

How to Import Excel File in C#, Figure 3: Read Range of Cells Read Range of Cells

For more details on reading and writing to cell values, check this tutorial read Excel file in C# example.

Import all Data from the Excel File

IronXL can be used to read Excel sheets at once using Rows and Columns indexes. The following IronXL code samples help to 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();
}
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();
}
Imports Microsoft.VisualBasic

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

' Traverse all rows of Excel WorkSheet
For i As Integer = 0 To sheet.Rows.Count() - 1
	' Traverse all columns of specific Row
	For j As Integer = 0 To sheet.Columns.Count() - 1
		' Get the values
		Dim val As String = sheet.Rows(i).Columns(j).Value.ToString()
		Console.Write("{0}" & vbTab, val)
	Next j
	Console.WriteLine()
Next i
$vbLabelText   $csharpLabel

Output File

How to Import Excel File in C#, Figure 4: The output console for reading an Excel file The output console for reading an Excel file

Add image alt text.

Summary

This article demonstrated how to import and read an Excel file in C# without any Microsoft Excel installed. It then considered multiple ways to read data from an Excel spreadsheet. IronXL also helps create Excel files in C# without any Excel installed.

IronXL provides an all-in-one solution for all Microsoft Excel document-related tasks to be implemented programmatically. You can perform formula calculation, string or number sorting, trimming and appending, find and replace, merge and unmerge, save files, etc. 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 like Excel data.

IronXL is available for a free trial and can be licensed for commercial use with its Lite package starting from $799 only.

常见问题解答

如何在不使用 Interop 的情况下在 C# 中导入和读取 Excel 文件?

您可以使用 IronXL 库在 C# 中导入和读取 Excel 文件。只需使用 WorkBook.Load("file.xlsx") 加载 Excel 文件即可访问并处理数据,无需安装微软 Excel。

IronXL 库兼容哪些平台?

IronXL 兼容所有 .NET 框架,并可用于包括 Windows、Linux、MacOS、Docker、Azure 和 AWS 在内的多个平台。

我可以使用 IronXL 编辑 Excel 文件而无需安装 Microsoft Excel 吗?

是的,IronXL 允许您在 C# 中以编程方式创建和编辑 Excel 文件,而无需在系统上安装 Microsoft Excel。

IronXL 可以处理哪些 Excel 格式?

IronXL 支持各种 Excel 文件格式,如 XLS、XLSX、CSV、TSV 等,能够轻松导入和操作数据。

在 C# 项目中使用 IronXL 有哪些先决条件?

要使用 IronXL,请确保已安装 Visual Studio。您可以通过 NuGet 软件包管理器添加 IronXL 到您的项目,或通过下载并引用 .NET Excel DLL。

如何在 C# 中使用 IronXL 加载 Excel 工作簿?

要在 C# 中加载 Excel 工作簿,可以使用 IronXL 的 WorkBook.Load("path/to/file.xlsx") 方法,可以打开并操作工作簿。

是否可以使用 IronXL 处理 Excel 公式?

可以,IronXL 可以在每次编辑工作表时无缝地处理和重新计算 Excel 公式,确保数据计算的准确性。

如何使用 IronXL 从特定单元格读取数据?

要从特定单元格读取数据,可以使用 IronXL 语法如 sheet["B2"].StringValue 来获取 B2 单元格的值。

我可以使用 IronXL 遍历 Excel 表格的单元格范围吗?

是的,您可以使用 IronXL 遍历单元格范围,使用语法如 foreach (var cell in sheet["A1:C3"]) 来逐个处理每个单元格。

如何将 IronXL 集成到 ASP.NET 应用程序中?

可以通过 NuGet 添加库并在项目中引用,在 ASP.NET 应用程序中轻松集成 IronXL,实现 Excel 文件操作。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。