如何使用 C# 在 Excel 中選取範圍 | IronXL

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

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

IronXL 讓 C# 開發人員能夠在不依賴 Office Interop 的情況下,選取並操作 Excel 的範圍、列與欄。 請使用簡單的語法,例如 workSheet["A1:C3"] 來選取範圍、GetRow() 來選取列,以及 GetColumn() 來選取欄。

快速入門:在 IronXL 中以單行選取儲存格範圍

在 IronXL 工作表中,只需單次呼叫 GetRange,即可擷取如"A1:C3"這類矩形範圍——無需迴圈,輕鬆簡單。 這是同時操作多個儲存格的最快方法。

  1. using NuGet 套件管理員安裝 https://www.nuget.org/packages/IronXl.Excel

    PM > Install-Package IronXl.Excel
  2. 請複製並執行此程式碼片段。

    var range = workSheet.GetRange("A1:C3");
  3. 部署至您的生產環境進行測試

    立即透過免費試用,在您的專案中開始使用 IronXL

    arrow pointer


如何在 IronXL 中選取不同類型的範圍?

透過 IronXL,您可以對選定的範圍執行各種操作,例如排序、計算和彙總。 此函式庫提供直觀的範圍選取方法,既能模擬 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 功能相仿的進階範圍選取情境:

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
  1. 運用範圍迭代以實現高效處理:
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 提供了能保留格式與公式的專用方法。

IronXL 入門指南

若要在您的專案中開始使用 IronXL 的範圍選取功能,請先參閱詳盡的入門指南。 透過 NuGet 套件管理員安裝 IronXL:

Install-Package IronXl.Excel

或使用 .NET CLI:

dotnet add package IronXl.Excel
dotnet add package IronXl.Excel
SHELL

範圍選取是 C# 中操作 Excel 的基礎。 透過 IronXL 直觀的 API,您可高效地選取、處理及轉換 Excel 資料,無需面對 Office Interop 的複雜性。無論是建立報表、分析資料,還是自動化試算表任務,掌握範圍選取功能將顯著提升您的工作效率。

常見問題

如何使用 C# 在 Excel 中選取一組儲存格?

透過 IronXL,您可以使用簡單的語法(例如 workSheet["A1:C3"] 或 workSheet.GetRange("A1:C3")選取一組儲存格。這讓您能夠選取矩形範圍,無需依賴 Office Interop。

我能否透過程式碼選取整行與整列?

是的,IronXL 提供了 GetRow() 和 GetColumn() 方法,用於選取 Excel 試算表中的整行與整列。這些方法可讓您透過程式化方式控制行與列的選取,且無需安裝 Excel。

如何在 C# 中合併多個儲存格範圍?

IronXL 允許您使用 '+' 運算子組合多個範圍。此功能讓您能輕鬆地透過程式化方式處理非連續的儲存格選取範圍。

我可以在選取的範圍上執行哪些操作?

using IronXL 選取範圍後,您可以執行各種操作,包括排序、數學運算、套用格式、遍歷儲存格,以及彙總資料(例如計算總和)。

如何對選取的範圍套用格式?

在 IronXL 中選取範圍後,您可以透過 Style 屬性套用格式。例如,您可以使用 range.Style.BackgroundColor 設定背景顏色,並透過 range.Style.Font.Bold = true 將文字設為粗體。

我可以遍歷選取範圍內的儲存格嗎?

是的,IronXL 允許您使用 foreach 迴圈遍歷選取範圍內的儲存格。每個儲存格皆可存取其值與位址,使您能輕鬆地逐個儲存格處理資料。

Curtis Chau
技術撰稿人

Curtis Chau 擁有卡爾頓大學(Carleton University)的電腦科學學士學位,專精於前端開發,並精通 Node.js、TypeScript、JavaScript 及 React。他熱衷於打造直觀且美觀的用戶介面,喜歡運用現代框架,並創建結構完善、視覺上吸引人的手冊。

除了開發工作之外,Curtis 對物聯網(IoT)抱有濃厚興趣,致力於探索整合硬體與軟體的創新方法。閒暇時,他喜歡玩遊戲和開發 Discord 機器人,將對科技的熱愛與創意相結合。

準備開始了嗎?
Nuget 下載 2,040,239 | 版本: 2026.5 just released
Still Scrolling Icon

還在滾動?

想要快速證明嗎? PM > Install-Package IronXl.Excel
執行一個樣本 看著您的數據變成電子表格。