跳至页脚内容
使用 IRONXL

如何在 C# 中管理 Excel 范围

通过编程方式处理Excel 文件可以显著提高 C# 应用程序的效率和自动化功能。 无论您是生成报告、处理数据还是动态创建复杂的电子表格,掌握 Excel 文件的操作都至关重要。 在本教程中,我们将重点介绍如何使用IronXL处理 Excel 区域。 我们将介绍如何在 Excel 文件中写入读取操作区域

如何在 C# 中读取 Excel 区域

  1. 安装 IronXL 库以处理 Excel 文件。
  2. 加载工作簿并指定工作表。
  3. 选择要读取的单元格范围。
  4. 从指定范围内提取和读取数据。

什么是 IronXL?

IronXL是一个全面的 C# 库,它简化了 Excel 文件的操作,提供了一系列功能,可实现电子表格数据的无缝集成和操作。 它具备读取写入修改Excel 文件的功能,无需安装 Microsoft Excel,从而实现跨平台兼容性。

IronXL 可以方便地从特定单元格区域或整个工作表中提取数据,并提供格式设置样式设置条件格式设置等高级功能。 IronXL 支持计算、公式和统计分析,使开发人员能够以编程方式高效地处理 Excel 操作,使其成为在 C# 应用程序中自动化以数据为中心的任务的不可或缺的工具。

C# 中 Excel 单元格区域的入门

首先,我们需要在应用程序中安装 IronXL 库。

安装 IronXL NuGet 包

您可以使用以下命令通过 NuGet 包管理器安装 IronXL:

Install-Package IronXL.Excel

上述命令将安装 IronXL 及其所有依赖项。

如何在 C# 中管理 Excel 区域:图 1

添加命名空间

在 Program.cs 类的顶部,或任何你想使用 IronXL 方法的地方,添加以下命名空间。

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

加载 Excel 工作簿

第一步是加载 Excel 工作簿。 以下代码会将 Excel 工作簿加载到我们的应用程序中。

static void Main(string[] args)
{
    // Load an existing Excel workbook
    var workbook = WorkBook.Load("test_excel.xlsx");

    // Retrieve the specified worksheet from the workbook
    var sheet = workbook.GetWorkSheet("Sheet1");
}
static void Main(string[] args)
{
    // Load an existing Excel workbook
    var workbook = WorkBook.Load("test_excel.xlsx");

    // Retrieve the specified worksheet from the workbook
    var sheet = workbook.GetWorkSheet("Sheet1");
}
Shared Sub Main(ByVal args() As String)
	' Load an existing Excel workbook
	Dim workbook = WorkBook.Load("test_excel.xlsx")

	' Retrieve the specified worksheet from the workbook
	Dim sheet = workbook.GetWorkSheet("Sheet1")
End Sub
$vbLabelText   $csharpLabel

第一行代码从名为"test_excel.xlsx"的文件中加载一个现有的Excel工作簿。 第二行从已加载的工作簿中检索名为"Sheet1"的工作表。

在本教程中,我将使用以下 Excel 文件。

如何在 C# 中管理 Excel 区域:图 2

从一系列数据中读取数据

现在,让我们读取指定单元格范围内的数据。

// Define a range from cell A2 to G10 in the worksheet
var range = sheet["A2:G10"];

// Iterate over each cell in the range and output its value
foreach (var item in range)
{
    Console.WriteLine(item);
}
// Define a range from cell A2 to G10 in the worksheet
var range = sheet["A2:G10"];

// Iterate over each cell in the range and output its value
foreach (var item in range)
{
    Console.WriteLine(item);
}
' Define a range from cell A2 to G10 in the worksheet
Dim range = sheet("A2:G10")

' Iterate over each cell in the range and output its value
For Each item In range
	Console.WriteLine(item)
Next item
$vbLabelText   $csharpLabel

第一行选择工作表中的特定范围地址(A2 到 G10),允许您同时处理多个 Excel 单元格。 foreach (var item in range)循环遍历此单元格范围内的每个单元格,从而实现高效的数据处理。

通过使用 Console.WriteLine(item);,代码将每个单元格的值打印到控制台,使得审查范围内的内容变得简单。 这种方法简化了数据处理,提高了代码可读性。

在区域中使用 Excel 公式

让我们选择一个特定的范围,并应用一些 Excel 公式。

// Define a range from cell F2 to F42 for statistical analysis
var range = sheet["F2:F42"];

// Output the minimum age within the range
Console.WriteLine($"Minimum Age: {range.Min()}");

// Output the maximum age within the range
Console.WriteLine($"Maximum Age: {range.Max()}");

// Output the average age, casting the average value to an integer
Console.WriteLine($"Average Age: {(int)range.Avg()}");
// Define a range from cell F2 to F42 for statistical analysis
var range = sheet["F2:F42"];

// Output the minimum age within the range
Console.WriteLine($"Minimum Age: {range.Min()}");

// Output the maximum age within the range
Console.WriteLine($"Maximum Age: {range.Max()}");

// Output the average age, casting the average value to an integer
Console.WriteLine($"Average Age: {(int)range.Avg()}");
Imports System

' Define a range from cell F2 to F42 for statistical analysis
Dim range = sheet("F2:F42")

' Output the minimum age within the range
Console.WriteLine($"Minimum Age: {range.Min()}")

' Output the maximum age within the range
Console.WriteLine($"Maximum Age: {range.Max()}")

' Output the average age, casting the average value to an integer
Console.WriteLine($"Average Age: {CInt(Math.Truncate(range.Avg()))}")
$vbLabelText   $csharpLabel

代码var range = sheet["F2:F42"];选择从 F2 到 F42 的单元格区域,以便对年龄数据进行统计分析。 使用range.Min()range.Max() ,可以高效地计算指定范围内的最小和最大年龄值,从而有助于人口统计分析。

此外, range.Avg()可以计算平均年龄,为数据解释提供有价值的统计指标。 这种方法简化了数据分析任务,使用户能够快速获取必要的统计信息,从而做出明智的决策。

如何在 C# 中管理 Excel 区域:图 3

从单个细胞读取数据

让我们读取单个细胞中的数据。

// Retrieve the value from cell B2 in the worksheet
var read_from_single_cell = sheet["B2"];

// Output the value in cell B2
Console.WriteLine($"The Value in Cell B2 is: {read_from_single_cell}");
// Retrieve the value from cell B2 in the worksheet
var read_from_single_cell = sheet["B2"];

// Output the value in cell B2
Console.WriteLine($"The Value in Cell B2 is: {read_from_single_cell}");
' Retrieve the value from cell B2 in the worksheet
Dim read_from_single_cell = sheet("B2")

' Output the value in cell B2
Console.WriteLine($"The Value in Cell B2 is: {read_from_single_cell}")
$vbLabelText   $csharpLabel

代码var read_from_single_cell = sheet["B2"];从工作表中检索存储在单元格 B2 中的值。 使用这种方法,您可以轻松访问 Excel 文件中的特定单元格值。

使用Console.WriteLine($"The Value in Cell B2 is: {read_from_single_cell}"); ,代码会将引用单元格的检索值打印到控制台,从而方便数据验证和调试。 这简化了从 Excel 文件中检索和显示单个单元格值的过程。

如何在 C# 中管理 Excel 区域:图 4

读取整列数据

让我们使用索引读取整列数据。

// Retrieve values from the column at index 2 (C column) 
var columnValues = sheet.GetColumn(2); // 2 is column index

// Iterate over each value in the column and output it
foreach (var columnValue in columnValues)
{
    Console.WriteLine(columnValue);
}
// Retrieve values from the column at index 2 (C column) 
var columnValues = sheet.GetColumn(2); // 2 is column index

// Iterate over each value in the column and output it
foreach (var columnValue in columnValues)
{
    Console.WriteLine(columnValue);
}
' Retrieve values from the column at index 2 (C column) 
Dim columnValues = sheet.GetColumn(2) ' 2 is column index

' Iterate over each value in the column and output it
For Each columnValue In columnValues
	Console.WriteLine(columnValue)
Next columnValue
$vbLabelText   $csharpLabel

代码var columnValues = sheet.GetColumn(2);检索工作表中索引为 2(C 列)的列中的所有值。 这样可以高效地访问 Excel 表格中特定列的所有值。

通过foreach循环遍历columnValues ,使用Console.WriteLine(columnValue); 这种方法便于处理和显示 Excel 文件中的列式数据,简化数据分析任务。

如何在 C# 中管理 Excel 区域:图 5

或者,我们也可以使用列名而不是索引来读取列中的数据。 请考虑以下示例:

// Retrieve values from the column with name "C"
var columnValues = sheet.GetColumn("C");
// Retrieve values from the column with name "C"
var columnValues = sheet.GetColumn("C");
' Retrieve values from the column with name "C"
Dim columnValues = sheet.GetColumn("C")
$vbLabelText   $csharpLabel

这样我们就可以指定多列了。

读取整行数据

让我们通过行号读取整行数据。

// Retrieve values from the row at index 1 (Row 2)
var rowValues = sheet.GetRow(1); // 1 is row index

// Iterate over each value in the row and output it
foreach (var rowValue in rowValues)
{
    Console.Write(rowValue + "  ");
}
// Retrieve values from the row at index 1 (Row 2)
var rowValues = sheet.GetRow(1); // 1 is row index

// Iterate over each value in the row and output it
foreach (var rowValue in rowValues)
{
    Console.Write(rowValue + "  ");
}
' Retrieve values from the row at index 1 (Row 2)
Dim rowValues = sheet.GetRow(1) ' 1 is row index

' Iterate over each value in the row and output it
For Each rowValue In rowValues
	Console.Write(rowValue & "  ")
Next rowValue
$vbLabelText   $csharpLabel

代码var rowValues = sheet.GetRow(1);从工作表中索引为 1(第 2 行)的单行中检索所有值,从而可以高效地访问特定行的数据。 通过foreach循环遍历rowValues ,使用Console.Write(rowValue + " ");将行中的每个值打印到控制台。

这种方法简化了从 Excel 文件中提取和显示行数据的过程,有助于数据分析和报告任务。 这样,我们就可以在不指定范围的情况下读取多个单元格的值。

如何在 C# 中管理 Excel 区域:图 6

将数据写入单元格或范围

我们可以将数据写入单元格和区域。 首先,我们将数据写入一个范围。

// Select a range from D2 to D14 for modification
var range = sheet["D2:D14"];

// Set the value for each cell in the range
range.Value = "Prefer Not to Say"; // Change Gender Value

// Save the modified workbook to persist changes
workbook.Save();
// Select a range from D2 to D14 for modification
var range = sheet["D2:D14"];

// Set the value for each cell in the range
range.Value = "Prefer Not to Say"; // Change Gender Value

// Save the modified workbook to persist changes
workbook.Save();
' Select a range from D2 to D14 for modification
Dim range = sheet("D2:D14")

' Set the value for each cell in the range
range.Value = "Prefer Not to Say" ' Change Gender Value

' Save the modified workbook to persist changes
workbook.Save()
$vbLabelText   $csharpLabel

代码var range = sheet["D2:D14"];选择从单元格 D2 到 D14 的范围,从而可以批量修改数据。 通过将range.Value设置为"不愿透露",可以有效地更新指定范围内每个单元格的性别值,从而最大限度地减少重复性任务。

后续的workbook.Save();命令可确保这些更改被持久保存,从而保持数据的一致性和完整性。 这种方法简化了批量更新,并确保了多个单元格之间的一致性,从而提高了数据管理效率。

现在,让我们向特定单元格写入数据。

// Set the value for cell B2
sheet["B2"].Value = "John";

// Save the workbook to persist the changes
workbook.Save();
// Set the value for cell B2
sheet["B2"].Value = "John";

// Save the workbook to persist the changes
workbook.Save();
' Set the value for cell B2
sheet("B2").Value = "John"

' Save the workbook to persist the changes
workbook.Save()
$vbLabelText   $csharpLabel

代码sheet["B2"].Value = "John";直接将值"John"赋值给 Excel 工作表中的单元格 B2,提供了一种简洁直接的方法来更新特定单元格的值。 这种方法简化了修改单个单元格内容的过程,提高了代码的可读性和效率。

如何在 C# 中管理 Excel 区域:图 7 - C# Excel 区域

结论

总之,掌握使用 IronXL 在 C# 中进行 Excel 区域操作可以显著提高应用程序的效率和自动化能力,从而简化数据处理、报表生成和动态电子表格创建等任务。

IronXL 具有强大的 Excel 文件读取、写入和操作功能,开发人员可以简化数据处理流程,并利用公式、格式设置和统计分析等高级功能。 此外,IronXL 还提供免费试用,确保其能够灵活且可扩展地满足各种项目需求。

常见问题解答

如何开始在 C# 中操作 Excel 范围?

要在 C# 中开始操作 Excel 范围,请使用 NuGet Package Manager 安装 IronXL 库,命令为:Install-Package IronXL.Excel。然后,您可以开始加载 Excel 工作簿并使用 IronXL 的全面 API 操作范围。

如何使用 IronXL 加载 Excel 工作簿?

您可以使用 WorkBook.Load 方法在 IronXL 中加载 Excel 工作簿,传递文件名作为参数,例如:var workbook = WorkBook.Load('test_excel.xlsx');

在 IronXL 中读取特定单元格范围的方法有哪些?

在 IronXL 中,您可以通过定义范围来读取特定的单元格范围,使用类似 sheet['A2:G10'] 的语法,并通过迭代来访问每个单元格的值。

如何对 Excel 范围内的数据进行统计分析?

使用 IronXL,您可以通过选择范围并应用如 range.Min()range.Max()range.Avg() 等方法来计算最小值、最大值和平均值,从而进行统计分析。

用 IronXL 将数据写入特定单元格的过程是什么?

要在 IronXL 中将数据写入特定单元格,可以直接为该单元格赋值,例如:sheet['B2'].Value = 'John';,然后保存工作簿以持久化更改。

在 IronXL 中不指定范围是否可以读取整个列的数据?

是的,IronXL 允许您使用 sheet.GetColumn(index)sheet.GetColumn('C') 读取整列的数据,使您可以使用索引或列名来检索数据。

如何使用 IronXL 从整个行提取数据?

要在 IronXL 中从整行提取数据,使用 sheet.GetRow(index) 并迭代检索到的值来访问数据。

IronXL 提供哪些高级 Excel 操作功能?

IronXL 提供高级功能,如格式化、样式、条件格式化,以及支持计算和公式,增强了在 C# 应用程序中对 Excel 文件的操作能力。

在购买之前是否可以试用 IronXL?

是的,IronXL 提供免费试用版,允许开发人员探索其功能并确定其对项目的适用性,无需任何初始费用。

IronXL 如何增强 C# 应用程序的自动化功能?

IronXL 通过使 Excel 文件的编程操作变得无缝连接,在 C# 应用程序中增强了自动化功能,这对于诸如数据处理、报告生成和动态电子表格创建等任务至关重要,无需安装 Microsoft Excel。

Curtis Chau
技术作家

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

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