跳至页脚内容
使用 IRONXL

如何在 C# 中打开 Excel 文件

IronXL 使 C# 开发人员无需安装 Microsoft Office 即可打开、读取和操作 Excel 文件。 只需使用WorkBook.Load()加载工作簿,访问工作表,并使用类似sheet["A1"]直观语法读取单元格值。

本教程探讨了如何在 C# 项目中使用 IronXL 打开和读取 Excel 文件,为初级开发人员提供处理 Excel 数据的全面示例和最佳实践。

IronXL Excel Library是什么?

IronXL是一个 .NET 库,它优先考虑易用性、准确性和速度。 它可以帮助您高效地打开、读取、创建编辑Excel 文件,而无需 MS Office Interop,因此对于希望在 C# 中使用 Excel 而无需 Interop 的开发人员来说,这是一个实用的选择。

IronXL 与所有 .NET Framework 以及LinuxmacOSDockerAzureAWS兼容。 您可以使用它来创建控制台应用程序、Web 应用程序和桌面应用程序,例如Blazor.NET MAUI,用于开发现代 Web 应用程序。它支持不同的工作簿格式,例如 XLS 和 XLSX 文件、XSLT 和 XLSM、CSV 和 TSV。

IronXL的主要特点是什么?

如何在 C# 中打开 Excel 文件?

开始之前我需要准备什么?

要在 C# 应用程序中使用 IronXL,请在本地计算机上安装以下组件:

  1. Visual Studio - 用于开发 C# .NET 应用程序的官方 IDE。 您可以从微软网站下载并安装 Visual Studio。 您也可以使用JetBrains ReSharper和 Rider 。 有关更多设置指导,请参阅入门概述
  2. IronXL - 帮助在 C# 中处理 Excel 表格的 Excel 库。 必须先将其安装到您的 C# 应用程序中才能使用。 您可以从NuGet 网站下载,也可以从 Visual Studio 中的"管理 NuGet 程序包"下载。 您也可以直接下载.NET Excel DLL文件。 有关许可实施,请参阅"使用许可证密钥"

我应该导入哪些命名空间?

安装好 Visual Studio 和 IronXL 后,在 C# 文件顶部添加以下代码行,以添加必要的 IronXL 命名空间:

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

要使用特定的 Excel 格式或高级功能,您可能还需要:

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
$vbLabelText   $csharpLabel

如何加载现有的Excel文件?

Excel 文件(也称为工作簿)由多个工作表组成,每个工作表都包含单元格值。 要打开并读取 Excel 文件,请使用WorkBook类的Load方法加载它。 LoadSpreadsheets功能支持多种格式。

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

这将工作簿初始化为WorkBook实例。 要打开特定的WorkSheet ,请从WorkSheets集合中检索它。 《管理工作表》指南提供了有关工作表操作的更多详细信息:

// 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
$vbLabelText   $csharpLabel

这将访问 Excel 文件中的第一个工作表,以便进行读取和写入操作。

Excel电子表格,显示5名员工的数据,包含姓名、职称和薪资三列,并带有格式化的表头和单元格边框。 Excel 文件

如何读取Excel单元格中的数据?

Excel 文件打开后,即可读取数据。 使用 IronXL 在 C# 中读取 Excel 文件中的数据非常简单。 您可以使用"选择范围"功能指定单元格引用来读取单元格值。

以下代码用于获取单元格的值:

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

译文如下:

Microsoft Visual Studio 调试控制台窗口显示已成功从 Excel 单元格 C2 中提取值"100000",并带有上下文输出消息。 读取 Excel

要从一系列单元格中读取数据,请使用循环遍历指定的范围。 "选择 Excel 区域"示例提供了更多模式:

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

访问单元格区域A2:A6中的每个值并将其打印到控制台。

! Microsoft Visual Studio 调试控制台,带有语法高亮显示,显示读取 Excel 单元格区域 A2:A6 的输出,其中包含员工姓名 John、Sara、Peter、Method 和 Katherine。 读取单元格范围

有关更详细的读写示例,请查看C# 中的 Excel 读取教程。 您还可以将 Excel 数据转换为数据表,以便更轻松地进行操作:

// 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"]}");
}
$vbLabelText   $csharpLabel

如何创建新的Excel文件?

IronXL 还方便创建新的工作簿以保存和检索数据。 《创建电子表格》指南提供了全面的示例。

只需一行代码即可创建一个新的 Excel 文件:

// 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";
$vbLabelText   $csharpLabel

接下来,创建一个工作表并向其中添加数据。 有关更高级的创建模式,请参阅创建新的 Excel 文件

如何向工作簿中添加工作表?

// 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");
$vbLabelText   $csharpLabel

这段代码会在工作簿中添加一个名为"GDPByCountry"的工作表,允许您添加单元格值。 了解更多关于管理工作表复制工作表的信息。

要为特定单元格设置值,请使用以下代码:

// 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");
$vbLabelText   $csharpLabel

最终输出结果为:

! Excel 电子表格显示单元格 A1 中填充了使用 C# 程序以编程方式添加的"示例"文本,同时显示"按国家/地区划分的 GDP"工作表标签,并且单元格高亮显示以指示添加的值。 向单元格添加值

使用不同的Excel格式

IronXL 支持多种 Excel 格式。 以下是如何处理不同文件类型的方法:

// 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
$vbLabelText   $csharpLabel

了解更多关于转换电子表格文件类型以及如何将 XLSX 转换为 CSV、JSON、XML 的信息

错误处理和最佳实践

处理Excel文件时,要实施适当的错误处理:

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}");
}
$vbLabelText   $csharpLabel

对于生产应用,请考虑设置日志记录并实现适当的错误处理模式

我们学到了什么?

本文演示了如何使用 IronXL 在 C# 中打开和读取 Excel 文件,例如 XLS 和 XLSX 文件。 IronXL 不需要在系统上安装 Microsoft Excel 即可执行与 Excel 相关的任务,因此非常适合Docker 部署Azure 函数

IronXL 提供了一个全面的 Excel 相关任务编程解决方案,包括公式计算、字符串排序、修剪、查找和替换、合并和取消合并保存文件等等。 您还可以设置单元格数据格式、使用条件格式以及 创建图表

要了解高级功能,请探索分组和取消分组命名区域超链接以及保护 Excel 文件。 完整的API 参考文档提供了所有功能的详细文档。

IronXL 提供30 天免费试用,并可授权用于商业用途。 IronXL 的 Lite 套餐起价为$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 机器人,将他对技术的热爱与创造力相结合。