如何使用 C# 在 Excel 中選擇區域進行Excel資料擷取
IronXL使 C# 開發人員能夠在不依賴 Office Interop 的情況下選擇和操作 Excel 區域、行和列,完成Excel資料擷取。 使用簡單的語法,例如 workSheet["A1:C3"] 來選擇範圍,GetRow() 來選擇行,以及 GetColumn() 來選擇列,以編程方式進行。
快速入門:在IronXL中一行程式碼選擇儲存格區域@@--AH2EG--@@
在IronXL工作表中,只需呼叫一次 GetRange 即可取得類似"A1:C3"的矩形區域-無需循環,輕鬆便捷。 這是同時操控多個細胞的最快方法。
最簡工作流程(5個步驟)
- 下載 C# 庫以選擇範圍
- 在 WorkSheet 物件後直接使用**workSheet ["A2:B8"]**可以選擇儲存格區域。
- 使用`GetRow`方法選擇工作表中的一行
- 使用`GetColumn`方法選擇給定工作表中的欄位。
- 使用"+"運算符可以輕鬆合併範圍。
如何在IronXL中選擇不同類型的量程?
使用IronXL,您可以對選定的範圍執行各種操作,例如排序、計算和聚合。 該程式庫提供了直覺的範圍選擇方法,這些方法與 Excel 的原生功能類似,同時也提供了程式控制。
範圍選擇是許多 Excel 操作的基礎。 無論您是進行數學計算、應用格式還是提取數據,選擇正確的單元格都是第一步。 IronXL 憑藉其靈活的範圍選擇 API,使這一過程變得簡單易行。
當套用修改或移動儲存格值的方法時,受影響的區域、行或列的值將會隨之更新。
如何選擇矩形區域的儲存格?
若要選擇從儲存格 A2 到 B8 的範圍,可以使用下列程式碼:
: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")
使用選定範圍
選定範圍後, 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}")
如需更複雜的電子表格操作,請參閱全面的 API 文件。
如何選擇整行?
若要選擇第 4 行,可以使用從零開始的索引方法。 這將包括第 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)
當您需要逐行處理資料時,行選擇功能尤其有用。例如,在載入電子表格資料進行分析時:
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
如何選擇整列?
若要選擇 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)
所有行和列索引位置均採用從零開始的索引。
在處理列式資料(例如財務報告或資料庫匯出)時,列選擇功能非常實用。 在建立包含計算列的新電子表格時,您可能會使用它:
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")
如何合併多個範圍?
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")
進階射程選擇技巧
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
在使用公式時,範圍選擇功能會變得更強大:
// 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()
最佳射程選擇實踐
在IronXL中使用爐灶時,請考慮以下性能和可靠性方面的建議:
-
當您知道所需的確切儲存格時,請使用特定的範圍位址。 這比選擇整行或整列效率更高。
- 選擇前驗證範圍邊界,以避免執行時錯誤:
// 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
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
對於複製儲存格區域等更複雜的場景, IronXL提供了專門的方法,可以保持格式和公式不變。
IronXL入門指南
若要開始在您的專案中使用 IronXL 的範圍選擇功能,請先閱讀全面的入門指南。 透過NuGet套件管理器安裝IronXL :
Install-Package IronXL.Excel
或使用.NET CLI:
dotnet add package IronXL.Excel
dotnet add package IronXL.Excel
在 C# 中,範圍選擇是 Excel 操作的基礎。 透過 IronXL 直覺的 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 環路遍歷選取範圍中的儲存格。每個單元格都提供存取其值和位址的功能,讓您可以輕鬆地逐個單元格處理資料。

