跳至页脚内容
使用 IRONXL

如何在 C# 中打开 Excel 文件

This tutorial will use IronXL as a main tool to open and read Excel files in C# projects.

IronXL Excel Library

IronXL is a .NET library that prioritizes ease of use, accuracy, and speed for its users. It helps you open, read, create, and edit Excel files with lightning-fast performance and without any errors. It works without MS Office Interop, which makes it a powerful tool for developers.

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

Some Important IronXL Features

  • Open, read, and search data in different formats (XLS/XLSX file/CSV/TSV).
  • Export Excel Worksheets to XLS/XLSX/CSV/TSV/JSON.
  • Encrypting and decrypting XLSX/XLSM/XLTX files with passwords.
  • Work with Excel sheets as System.Data.DataSet and System.Data.DataTable objects.
  • Excel file formulas are recalculated automatically each time a sheet is edited.
  • Easy spreadsheet data editing with an intuitive cell-range-based syntax (e.g., WorkSheet["A1:B10"]).
  • Sort Cell Ranges, Columns, and Rows.
  • Styling Cells - Font, Font Size, Background color, Border, Alignment, and Numbering formats.

How to open an Excel file in C#?

Prerequisites

To use IronXL in C# applications, install the following components on your local 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. You can also use Jetbrains ReSharper & Rider.
  2. IronXL - It is the Excel library that helps to work with Excel sheets at a given path 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 tools. You can also download the .NET Excel DLL file directly.

Adding Necessary Namespaces

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

Open an Existing Excel file in C#

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.

// 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 initializes the workbook as a WorkBook instance. To open a specific WorkSheet, retrieve it from the WorkSheets collection:

// Access the first worksheet in the workbook
WorkSheet sheet = workbook.WorkSheets.First();
// Access the first worksheet in the workbook
WorkSheet sheet = workbook.WorkSheets.First();
' Access the first worksheet in the workbook
Dim sheet As WorkSheet = workbook.WorkSheets.First()
$vbLabelText   $csharpLabel

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

How to Open Excel File in C#, Figure 1: Excel File Excel File

Read Excel Files in C#

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

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;

// Display the value in the console
Console.WriteLine(cellValue);
// Select the cell using Excel notation and retrieve its integer value
int cellValue = sheet["C2"].IntValue;

// Display the value in the console
Console.WriteLine(cellValue);
' Select the cell using Excel notation and retrieve its integer value
Dim cellValue As Integer = sheet("C2").IntValue

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

The output is as follows:

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

To read data from a range of cells, use a loop to iterate through the specified range:

// 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);
}
// 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);
}
' 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 cell
$vbLabelText   $csharpLabel

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

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

For more detailed reading and writing examples, check the Excel reading tutorial in C#.

Create a New Workbook

IronXL also facilitates creating new workbooks for data saving and retrieving.

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);
// Create a new workbook with the XLSX format
WorkBook workBook = new WorkBook(ExcelFileFormat.XLSX);
' Create a new workbook with the XLSX format
Dim workBook As New WorkBook(ExcelFileFormat.XLSX)
$vbLabelText   $csharpLabel

Next, create a worksheet and add data to it.

Create a New Worksheet

// Create a worksheet named "GDPByCountry" in the workbook
WorkSheet workSheet = workBook.CreateWorkSheet("GDPByCountry");
// Create a worksheet named "GDPByCountry" in the workbook
WorkSheet workSheet = workBook.CreateWorkSheet("GDPByCountry");
' Create a worksheet named "GDPByCountry" in the workbook
Dim workSheet As WorkSheet = workBook.CreateWorkSheet("GDPByCountry")
$vbLabelText   $csharpLabel

This code adds a worksheet named "GDPByCountry" to the workbook, allowing you to add cell values.

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

// Set the value of cell A1 to "Example"
workSheet["A1"].Value = "Example";
// Set the value of cell A1 to "Example"
workSheet["A1"].Value = "Example";
' Set the value of cell A1 to "Example"
workSheet("A1").Value = "Example"
$vbLabelText   $csharpLabel

The final output is:

How to Open Excel File in C#, Figure 4: Add Value to Cell Add Value to Cell

Summary

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.

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.

IronXL is available for a free 30-day trial and can be licensed for commercial use. IronXL's Lite package starts from $799.

常见问题解答

如何在 C# 中打开 Excel 文件而不使用 Interop?

您可以利用 IronXL 库在 C# 中打开 Excel 文件,无需使用 Interop。使用 WorkBook.Load 方法将 Excel 文件加载到 WorkBook 实例中,以便访问和操作文件中的数据。

这个 C# Excel 库兼容哪些文件格式?

IronXL 支持多种 Excel 文件格式,包括 XLS、XLSX、CSV 和 TSV。这使开发人员能够在 C# 应用程序中灵活地打开、读取和写入这些格式。

我能用这个库在 C# 中编辑 Excel 文件吗?

是的,您可以使用 IronXL 编辑 Excel 文件。加载工作簿后,您可以修改数据、添加新工作表,然后将更改保存回文件或以各种格式导出。

如何为我的 C# 项目安装这个库?

要在您的 C# 项目中安装 IronXL,您可以使用 Visual Studio 中的 NuGet 包管理器来添加库。或者,您可以下载 .NET Excel DLL 并在项目中引用它。

能用这个库加密 Excel 文件吗?

是的,IronXL 允许你加密和解密 Excel 文件。您可以使用密码保护 Excel 文档,以便在文件操作期间保护敏感数据。

这个库支持 Excel 表中的公式重新计算吗?

IronXL 支持自动公式重新计算,确保对数据的任何更改都自动更新公式,就像在 Excel 中一样。

我如何使用这个库读取 Excel 工作表中的特定单元格值?

要使用 IronXL 读取特定单元格值,您可以使用 Excel 表达式引用单元格。例如,sheet["A1"].StringValue 将从单元格 A1 中检索字符串值。

这个库可以跨不同操作系统使用吗?

是的,IronXL 兼容多个操作系统,包括 Windows、Linux 和 macOS。它还支持在 Docker、Azure 和 AWS 环境中的部署。

这个库相对于 MS Office Interop 有哪些优点?

IronXL 提供了相对于 MS Office Interop 的几个优点,例如不需要在系统上安装 Excel,在服务器环境中表现更好,并更易于在现代 .NET 应用程序中使用。

这个 C# Excel 库有免费试用版吗?

是的,IronXL 提供 30 天的免费试用,让您在为您的项目决定商业许可证之前测试其功能和能力。

Curtis Chau
技术作家

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

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