如何使用C#选择Excel中的范围 | IronXL

如何使用 C# 在 Excel 中选择范围

This article was translated from English: Does it need improvement?
Translated
View the article in English

IronXL.Excel 使 C# 开发人员能够在不依赖 Office Interop 的情况下选择和操作 Excel 范围、行和列。 使用简单的语法,如 workSheet["A1:C3"] 来选择范围,GetRow() 来选择行,GetColumn() 来选择列。

快速入门:在 IronXL 中一行选择单元格区域

在 IronXL 工作表中,只需调用一次GetRange函数即可获取类似"A1:C3"的矩形区域——无需循环,轻松便捷。 这是同时开始操作多个单元格的最快方法。

Nuget Icon立即开始使用 NuGet 创建 PDF 文件:

  1. 使用 NuGet 包管理器安装 IronXL

    PM > Install-Package IronXL.Excel

  2. 复制并运行这段代码。

    var range = workSheet.GetRange("A1:C3");
  3. 部署到您的生产环境中进行测试

    立即开始在您的项目中使用 IronXL,免费试用!
    arrow pointer


如何在 IronXL 中选择不同类型的范围?

使用 IronXL.Excel,您可以对选定的范围执行各种操作,如排序、计算和聚合。 该库提供了直观的范围选择方法,既能反映 Excel 的本地功能,又能提供程序控制。

范围选择是 Excel 许多操作的基础。 无论您是执行 数学计算、应用格式化还是提取数据,选择正确的单元格都是您的第一步。IronXL 通过其灵活的单元格区域选择 API 使这一过程变得简单明了。

当应用修改或移动单元格值的方法时,受影响的区域、行或列的值将相应更新。

IronXL 允许我们使用"+"运算符组合多个 IronXL.Ranges.Range。

如何选择单元格的矩形范围?

要选择A2B8单元格区域,可以使用以下代码:

:path=/static-assets/excel/content-code-examples/how-to/select-range-range.cs
using IronXL;
using System.Linq;

WorkBook workBook = WorkBook.Load("sample.xls");
WorkSheet workSheet = workBook.WorkSheets.First();

// Get range from worksheet
var range = workSheet["A2:B8"];
Imports IronXL
Imports System.Linq

Private workBook As WorkBook = WorkBook.Load("sample.xls")
Private workSheet As WorkSheet = workBook.WorkSheets.First()

' Get range from worksheet
Private range = workSheet("A2:B8")
$vbLabelText   $csharpLabel
电子表格显示范围 B2:C8,以粉红色突出显示,演示在样本数据网格中的可视化选择

使用选定的范围

选择范围后,IronXL 提供了许多可以执行的操作:

using IronXL;
using System;
using System.Linq;

// Load an existing spreadsheet
WorkBook workBook = WorkBook.Load("sample.xlsx");
WorkSheet workSheet = workBook.WorkSheets.First();

// Select a range and perform operations
var range = workSheet["A1:C5"];

// Apply formatting to the entire range
range.Style.BackgroundColor = "#E8F5E9";
range.Style.Font.Bold = true;

// Iterate through cells in the range
foreach (var cell in range)
{
    Console.WriteLine($"Cell {cell.AddressString}: {cell.Value}");
}

// Get sum of numeric values in the range
decimal sum = range.Sum();
Console.WriteLine($"Sum of range: {sum}");
using IronXL;
using System;
using System.Linq;

// Load an existing spreadsheet
WorkBook workBook = WorkBook.Load("sample.xlsx");
WorkSheet workSheet = workBook.WorkSheets.First();

// Select a range and perform operations
var range = workSheet["A1:C5"];

// Apply formatting to the entire range
range.Style.BackgroundColor = "#E8F5E9";
range.Style.Font.Bold = true;

// Iterate through cells in the range
foreach (var cell in range)
{
    Console.WriteLine($"Cell {cell.AddressString}: {cell.Value}");
}

// Get sum of numeric values in the range
decimal sum = range.Sum();
Console.WriteLine($"Sum of range: {sum}");
Imports IronXL
Imports System
Imports System.Linq

' Load an existing spreadsheet
Dim workBook As WorkBook = WorkBook.Load("sample.xlsx")
Dim workSheet As WorkSheet = workBook.WorkSheets.First()

' Select a range and perform operations
Dim range = workSheet("A1:C5")

' Apply formatting to the entire range
range.Style.BackgroundColor = "#E8F5E9"
range.Style.Font.Bold = True

' Iterate through cells in the range
For Each cell In range
    Console.WriteLine($"Cell {cell.AddressString}: {cell.Value}")
Next

' Get sum of numeric values in the range
Dim sum As Decimal = range.Sum()
Console.WriteLine($"Sum of range: {sum}")
$vbLabelText   $csharpLabel

有关电子表格的更复杂操作,请参阅 全面的 API 文档

如何选择整行?

要选择第 4 行,可以使用从零开始索引的GetRow(3)方法。 这将包括第 4 行中的所有单元格,即使其他行中的某些对应单元格为空。

:path=/static-assets/excel/content-code-examples/how-to/select-range-row.cs
using IronXL;
using System.Linq;

WorkBook workBook = WorkBook.Load("sample.xls");
WorkSheet workSheet = workBook.WorkSheets.First();

// Get row from worksheet
var row = workSheet.GetRow(3);
Imports IronXL
Imports System.Linq

Private workBook As WorkBook = WorkBook.Load("sample.xls")
Private workSheet As WorkSheet = workBook.WorkSheets.First()

' Get row from worksheet
Private row = workSheet.GetRow(3)
$vbLabelText   $csharpLabel
选中第 4 行的电子表格,显示单元格 B4 至 F4 周围的红色边框以演示行选择

当您需要逐行处理数据时,行选择尤其有用。例如,在 加载电子表格数据进行分析时:

using IronXL;
using System;

WorkBook workBook = WorkBook.Load("data.xlsx");
WorkSheet workSheet = workBook.WorkSheets.First();

// Process each row
for (int i = 0; i < workSheet.RowCount; i++)
{
    var row = workSheet.GetRow(i);

    // Skip empty rows
    if (row.IsEmpty) continue;

    // Process row data
    foreach (var cell in row)
    {
        // Your processing logic here
        Console.Write($"{cell.Value}\t");
    }
    Console.WriteLine();
}
using IronXL;
using System;

WorkBook workBook = WorkBook.Load("data.xlsx");
WorkSheet workSheet = workBook.WorkSheets.First();

// Process each row
for (int i = 0; i < workSheet.RowCount; i++)
{
    var row = workSheet.GetRow(i);

    // Skip empty rows
    if (row.IsEmpty) continue;

    // Process row data
    foreach (var cell in row)
    {
        // Your processing logic here
        Console.Write($"{cell.Value}\t");
    }
    Console.WriteLine();
}
Imports IronXL
Imports System
Imports System.Linq

Dim workBook As WorkBook = WorkBook.Load("data.xlsx")
Dim workSheet As WorkSheet = workBook.WorkSheets.First()

' Process each row
For i As Integer = 0 To workSheet.RowCount - 1
    Dim row = workSheet.GetRow(i)

    ' Skip empty rows
    If row.IsEmpty Then Continue For

    ' Process row data
    For Each cell In row
        ' Your processing logic here
        Console.Write($"{cell.Value}" & vbTab)
    Next
    Console.WriteLine()
Next
$vbLabelText   $csharpLabel

如何选择整个列?

要选择 C 列,您可以使用 GetColumn(2) 方法或指定范围地址为 workSheet["C:C"]。 与 GetRow 方法一样,它将包括所有相关单元格,无论是否已填入指定列。

:path=/static-assets/excel/content-code-examples/how-to/select-range-column.cs
using IronXL;
using System.Linq;

WorkBook workBook = WorkBook.Load("sample.xls");
WorkSheet workSheet = workBook.WorkSheets.First();

// Get column from worksheet
var column = workSheet.GetColumn(2);
Imports IronXL
Imports System.Linq

Private workBook As WorkBook = WorkBook.Load("sample.xls")
Private workSheet As WorkSheet = workBook.WorkSheets.First()

' Get column from worksheet
Private column = workSheet.GetColumn(2)
$vbLabelText   $csharpLabel
电子表格,列 C 用红色突出显示,显示如何在范围选择示例中选择整列

所有行和列索引位置均采用从零开始的索引。

列选择在处理列式数据(如财务报告或数据库导出)时非常有用。 您可能会在创建带有计算列的新电子表格时使用它:

using IronXL;
using System;

// Create a new workbook
WorkBook workBook = WorkBook.Create();
WorkSheet workSheet = workBook.CreateWorkSheet("Data");

// Add header row
workSheet["A1"].Value = "Quantity";
workSheet["B1"].Value = "Price";
workSheet["C1"].Value = "Total";

// Add sample data
for (int i = 2; i <= 10; i++)
{
    workSheet[$"A{i}"].Value = i - 1;
    workSheet[$"B{i}"].Value = 10.5 * (i - 1);
}

// Select the Total column and apply formula
var totalColumn = workSheet.GetColumn(2); // Column C
for (int i = 2; i <= 10; i++)
{
    workSheet[$"C{i}"].Formula = $"=A{i}*B{i}";
}

workBook.SaveAs("calculations.xlsx");
using IronXL;
using System;

// Create a new workbook
WorkBook workBook = WorkBook.Create();
WorkSheet workSheet = workBook.CreateWorkSheet("Data");

// Add header row
workSheet["A1"].Value = "Quantity";
workSheet["B1"].Value = "Price";
workSheet["C1"].Value = "Total";

// Add sample data
for (int i = 2; i <= 10; i++)
{
    workSheet[$"A{i}"].Value = i - 1;
    workSheet[$"B{i}"].Value = 10.5 * (i - 1);
}

// Select the Total column and apply formula
var totalColumn = workSheet.GetColumn(2); // Column C
for (int i = 2; i <= 10; i++)
{
    workSheet[$"C{i}"].Formula = $"=A{i}*B{i}";
}

workBook.SaveAs("calculations.xlsx");
Imports IronXL
Imports System

' Create a new workbook
Dim workBook As WorkBook = WorkBook.Create()
Dim workSheet As WorkSheet = workBook.CreateWorkSheet("Data")

' Add header row
workSheet("A1").Value = "Quantity"
workSheet("B1").Value = "Price"
workSheet("C1").Value = "Total"

' Add sample data
For i As Integer = 2 To 10
    workSheet($"A{i}").Value = i - 1
    workSheet($"B{i}").Value = 10.5 * (i - 1)
Next

' Select the Total column and apply formula
Dim totalColumn = workSheet.GetColumn(2) ' Column C
For i As Integer = 2 To 10
    workSheet($"C{i}").Formula = $"=A{i}*B{i}"
Next

workBook.SaveAs("calculations.xlsx")
$vbLabelText   $csharpLabel

如何组合多个范围?

IronXL 提供了使用"+"运算符组合多个IronXL.Ranges.Range对象的灵活性。 通过使用 "+"操作符,您可以轻松地连接或合并范围以创建新的范围。 当您需要对非连续单元格进行操作时,该功能尤其有用。 有关高级组合技术,请参阅 组合 Excel 范围示例

不支持直接使用"+"运算符合并行和列。

合并范围会修改原始范围。 下面的代码片段中,变量range将被修改以包含合并后的范围。

:path=/static-assets/excel/content-code-examples/how-to/select-range-combine-range.cs
using IronXL;
using System.Linq;

WorkBook workBook = WorkBook.Load("sample.xls");
WorkSheet workSheet = workBook.WorkSheets.First();

// Get range from worksheet
var range = workSheet["A2:B2"];

// Combine two ranges
var combinedRange = range + workSheet["A5:B5"];
Imports IronXL
Imports System.Linq

Private workBook As WorkBook = WorkBook.Load("sample.xls")
Private workSheet As WorkSheet = workBook.WorkSheets.First()

' Get range from worksheet
Private range = workSheet("A2:B2")

' Combine two ranges
Private combinedRange = range + workSheet("A5:B5")
$vbLabelText   $csharpLabel

高级范围选择技巧

IronXL.Excel 支持复杂的范围选择方案,与 Excel 的功能如出一辙:

using IronXL;
using System;
using System.Linq;

WorkBook workBook = WorkBook.Load("data.xlsx");
WorkSheet workSheet = workBook.WorkSheets.First();

// Select multiple non-adjacent ranges
var headerRange = workSheet["A1:E1"];
var dataRange1 = workSheet["A5:E10"];
var dataRange2 = workSheet["A15:E20"];

// Combine ranges for batch operations
var combinedData = dataRange1 + dataRange2;

// Apply consistent formatting across combined ranges
combinedData.Style.BottomBorder.Type = IronXL.Styles.BorderType.Thin;
combinedData.Style.Font.Height = 11;

// Copy formatting from one range to another
var sourceFormat = headerRange.Style;
dataRange1.First().Style = sourceFormat;
using IronXL;
using System;
using System.Linq;

WorkBook workBook = WorkBook.Load("data.xlsx");
WorkSheet workSheet = workBook.WorkSheets.First();

// Select multiple non-adjacent ranges
var headerRange = workSheet["A1:E1"];
var dataRange1 = workSheet["A5:E10"];
var dataRange2 = workSheet["A15:E20"];

// Combine ranges for batch operations
var combinedData = dataRange1 + dataRange2;

// Apply consistent formatting across combined ranges
combinedData.Style.BottomBorder.Type = IronXL.Styles.BorderType.Thin;
combinedData.Style.Font.Height = 11;

// Copy formatting from one range to another
var sourceFormat = headerRange.Style;
dataRange1.First().Style = sourceFormat;
Imports IronXL
Imports System
Imports System.Linq

Dim workBook As WorkBook = WorkBook.Load("data.xlsx")
Dim workSheet As WorkSheet = workBook.WorkSheets.First()

' Select multiple non-adjacent ranges
Dim headerRange = workSheet("A1:E1")
Dim dataRange1 = workSheet("A5:E10")
Dim dataRange2 = workSheet("A15:E20")

' Combine ranges for batch operations
Dim combinedData = dataRange1 + dataRange2

' Apply consistent formatting across combined ranges
combinedData.Style.BottomBorder.Type = IronXL.Styles.BorderType.Thin
combinedData.Style.Font.Height = 11

' Copy formatting from one range to another
Dim sourceFormat = headerRange.Style
dataRange1.First().Style = sourceFormat
$vbLabelText   $csharpLabel

使用公式时,范围选择变得更加强大:

// Select a range for formula application
var calculationRange = workSheet["D2:D20"];

// Apply formulas that reference other ranges
for (int i = 2; i <= 20; i++)
{
    workSheet[$"D{i}"].Formula = $"=SUM(A{i}:C{i})";
}

// Use range in aggregate functions
var sumRange = workSheet["B2:B20"];
decimal totalSum = sumRange.Sum();
decimal average = sumRange.Avg();
decimal max = sumRange.Max();
// Select a range for formula application
var calculationRange = workSheet["D2:D20"];

// Apply formulas that reference other ranges
for (int i = 2; i <= 20; i++)
{
    workSheet[$"D{i}"].Formula = $"=SUM(A{i}:C{i})";
}

// Use range in aggregate functions
var sumRange = workSheet["B2:B20"];
decimal totalSum = sumRange.Sum();
decimal average = sumRange.Avg();
decimal max = sumRange.Max();
Imports System

' Select a range for formula application
Dim calculationRange = workSheet("D2:D20")

' Apply formulas that reference other ranges
For i As Integer = 2 To 20
    workSheet($"D{i}").Formula = $"=SUM(A{i}:C{i})"
Next

' Use range in aggregate functions
Dim sumRange = workSheet("B2:B20")
Dim totalSum As Decimal = sumRange.Sum()
Dim average As Decimal = sumRange.Avg()
Dim max As Decimal = sumRange.Max()
$vbLabelText   $csharpLabel

范围选择的最佳实践

在 IronXL 中使用范围时,请考虑这些性能和可靠性提示:

1.当您知道所需的确切单元格时,请使用特定的单元格区域地址。 这比选择整行或整列更有效。

2.在选择前验证范围边界,以避免运行时出错:

// Check if range exists before selection
int lastRow = workSheet.RowCount;
int lastColumn = workSheet.ColumnCount;

if (lastRow >= 10 && lastColumn >= 3)
{
    var safeRange = workSheet["A1:C10"];
    // Process range
}
// Check if range exists before selection
int lastRow = workSheet.RowCount;
int lastColumn = workSheet.ColumnCount;

if (lastRow >= 10 && lastColumn >= 3)
{
    var safeRange = workSheet["A1:C10"];
    // Process range
}
' Check if range exists before selection
Dim lastRow As Integer = workSheet.RowCount
Dim lastColumn As Integer = workSheet.ColumnCount

If lastRow >= 10 AndAlso lastColumn >= 3 Then
    Dim safeRange = workSheet("A1:C10")
    ' Process range
End If
$vbLabelText   $csharpLabel

3.利用范围迭代实现高效处理:

var dataRange = workSheet["A1:E100"];

// Efficient: Process in batches
foreach (var cell in dataRange)
{
    if (cell.IsNumeric)
    {
        cell.Value = (decimal)cell.Value * 1.1; // 10% increase
    }
}
var dataRange = workSheet["A1:E100"];

// Efficient: Process in batches
foreach (var cell in dataRange)
{
    if (cell.IsNumeric)
    {
        cell.Value = (decimal)cell.Value * 1.1; // 10% increase
    }
}
Dim dataRange = workSheet("A1:E100")

' Efficient: Process in batches
For Each cell In dataRange
    If cell.IsNumeric Then
        cell.Value = CType(cell.Value, Decimal) * 1.1D ' 10% increase
    End If
Next
$vbLabelText   $csharpLabel

对于复制单元格区域等更复杂的情况,IronXL.Excel 提供了专门的方法来维护格式和公式。

IronXL入门指南

要开始在您的项目中使用 IronXL.Excel 的一系列选择功能,请从 全面的入门指南开始。 通过 NuGet 包管理器安装 IronXL:

Install-Package IronXL.Excel

或使用.NET CLI:

dotnet add package IronXL.Excel
dotnet add package IronXL.Excel
SHELL

范围选择是 C# 中 Excel 操作的基础。 有了 IronXL.Excel 直观的应用程序接口,您就可以高效地选择、操作和转换 Excel 数据,而无需进行复杂的 Office Interop。无论您是在构建报表、分析数据,还是在自动执行电子表格任务,掌握范围选择功能都将大大提高您的工作效率。

常见问题解答

如何使用 C# 在 Excel 中选择单元格区域?

使用 IronXL,您可以使用 workSheet["A1:C3"] 或 workSheet.GetRange("A1:C3") 等简单语法选择单元格区域。这样,您就可以选择矩形范围,而无需依赖 Office Interop。

能否以编程方式选择整行整列?

是的,IronXL.Excel 提供了 GetRow() 和 GetColumn() 方法,用于选择 Excel 工作表中的整行和整列。这些方法可对行和列的选择进行编程控制,而无需安装 Excel。

如何在 C# 中组合多个单元格范围?

IronXL 允许您使用 "+"运算符组合多个范围。该功能可让您轻松地以编程方式处理非连续的单元格选区。

我可以对选定的范围执行哪些操作?

使用 IronXL 选定范围后,您可以执行各种操作,包括排序、数学计算、应用格式化、迭代单元格以及计算总和等汇总数据。

如何对选定范围应用格式化?

在 IronXL 中选择范围后,您可以使用样式属性应用格式化。例如,您可以使用 range.Style.BackgroundColor 设置背景颜色,使用 range.Style.Font.Bold = true 使文本加粗。

能否遍历选定范围内的单元格?

是的,IronXL 允许您使用 foreach 循环遍历选定范围内的单元格。每个单元格都提供对其值和地址的访问,因此可以轻松地逐个单元格处理数据。

Curtis Chau
技术作家

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

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

准备开始了吗?
Nuget 下载 1,846,091 | 版本: 2026.2 刚刚发布