如何使用 C# 選擇 Excel 中的範圍 | IronXL

如何在 Excel 中使用 C# 選擇範圍

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 的一系列選擇功能,請從 全面的入門指南開始。 透過 NuGet 套件管理員安裝 IronXL:

Install-Package IronXL.Excel

或使用 .NET CLI:

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

範圍選擇是 C# 中 Excel 操作的基礎。 透過 IronXL.Excel 直觀的 API,您可以有效率地選擇、處理和轉換 Excel 資料,而不需要 Office Interop 的複雜性。無論您是要建立報表、分析資料或自動化試算表工作,掌握範圍選擇都能大幅提升您的生產力。

常見問題解答

如何使用 C# 在 Excel 中選擇一個儲存格範圍?

使用 IronXL,您可以使用工作表["A1:C3「]或工作表.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 對製作直覺且美觀的使用者介面充滿熱情,他喜歡使用現代化的架構,並製作結構良好且視覺上吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 也有濃厚的興趣,他喜歡探索整合硬體與軟體的創新方式。在空閒時間,他喜歡玩遊戲和建立 Discord bots,將他對技術的熱愛與創意結合。

準備好開始了嗎?
Nuget 下載 1,846,091 | 版本: 2026.2 剛剛發布