在 C# 中如何管理 Excel 範圍
使用Excel文件進行程式化操作可以顯著提高您的C#應用程式的效率和自動化能力。 無論您是在生成報告、處理資料,還是動態建立複雜的電子表格,掌握Excel文件的操作都是至關重要的。 在本教程中,我們將重點放在使用IronXL來處理Excel範圍。 我們將涵蓋如何在Excel文件中編寫、讀取和操作範圍。
How to Read Excel Ranges in C
- 安裝IronXL程式庫以處理Excel文件。
- 載入工作簿並指定工作表。
- 選擇要讀取的儲存格範圍。
- 從指定範圍中提取和讀取資料。
什麼是IronXL?
IronXL是一個為C#設計的綜合程式庫,可以簡化Excel文件的處理,提供一系列功能,便於電子表格資料的無縫整合和操作。 其功能包括讀取、編寫和修改Excel文件,無需安裝Microsoft Excel,實現跨平台相容性。
IronXL便於從特定的儲存格、範圍或整個工作表中提取資料,以及執行如格式化、樣式設計和條件格式化等高級功能。 IronXL支持計算、公式和統計分析,賦予開發人員以程式方式高效處理Excel操作,使其成為自動化C#應用內資料中心任務的不可或缺的工具。
Getting Started with Excel Range of cells in C
首先,我們需要在我們的應用程式中安裝IronXL程式庫。
安裝IronXL NuGet套件
您可以通過NuGet套件管理器使用以下命令安裝IronXL:
Install-Package IronXL.Excel
上述命令將與其所有依賴項一起安裝IronXL。

新增命名空間
在Program.cs類頂部或任何您希望使用IronXL方法的地方新增以下命名空間。
using IronXL;
using IronXL;
Imports IronXL
載入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
第一行從名為"test_excel.xlsx"的文件中載入現有的Excel工作簿。 第二行從載入的工作簿中檢索名為"Sheet1"的工作表。
在本教程中,我將使用以下Excel文件。

從範圍讀取資料
現在,讓我們讀取指定儲存格範圍內的資料。
// 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
第一行選擇工作表中的一個特定範圍地址(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()))}")
程式碼var range = sheet["F2:F42"];選擇從F2到F42的儲存格範圍,便於年齡資料的統計分析。 使用range.Max(),它能有效地計算指定範圍內的最低和最高年齡值,有助於人口統計分析。
此外,range.Avg()計算平均年齡,為資料解釋提供寶貴的統計指標。 這種方法簡化了資料分析任務,快速獲得關鍵的統計資訊,便於做出明智的決策。

從單一儲存格讀取資料
讓我們從單一儲存格中讀取資料。
// 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}")
程式碼var read_from_single_cell = sheet["B2"];從工作表中檢索儲存於儲存格B2的值。 使用這種方法,您可以輕鬆存取Excel文件中的特定儲存格值。
借助Console.WriteLine($"The Value in Cell B2 is: {read_from_single_cell}");,程式碼將檢索到的參考儲存格的值列印到控制台,便於資料驗證和除錯。 這簡化了從Excel文件檢索和顯示單個儲存格值的過程。

從整列讀取資料
讓我們使用索引從整列讀取資料。
// 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
程式碼var columnValues = sheet.GetColumn(2);從工作表中的索引位置2(C列)檢索所有值。 這允許您有效地存取Excel工作表中特定列中的所有值。
通過Console.WriteLine(columnValue);列印到控制台。 這種方法有助於處理和顯示Excel文件中的列狀資料,簡化資料分析任務。

或者,我們還可以使用列名而不是索引來讀取列資料。 請參考以下範例:
// 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")
以這種方式,我們可以指定多個列。
從整行讀取資料
讓我們通過使用行號從整行讀取資料。
// 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
程式碼var rowValues = sheet.GetRow(1);從工作表中的索引位置1(第2行)檢索所有值,實現行特定資料的高效存取。 通過Console.Write(rowValue + " ");列印到控制台。
這種方法簡化了從Excel文件中提取和顯示行資料的過程,援助於資料分析和報告任務。 以這種方式,我們可以在不指定範圍的情況下從多個儲存格中讀取值。

將資料寫入儲存格或範圍
我們可以將資料寫入儲存格和範圍。 首先,我們將資料寫入一個範圍。
// 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()
程式碼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()
程式碼sheet["B2"].Value = "John";直接將值"John"分配給Excel工作表中的儲存格B2,為更新特定儲存格值提供簡明扼要的方法。 這種方法簡化了修改單個儲存格內容的過程,提高了程式碼的可讀性和效率。

結論
總之,使用IronXL在C#中掌握Excel範圍操作可以顯著提高應用程式的效率和自動化能力,便於完成資料處理、報告生成和動態電子表格建立等任務。
憑藉IronXL在讀取、寫入和操作Excel文件方面的強大功能,開發人員可以簡化資料處理流程,並利用公式、格式化以及統計分析等高級功能。 此外,IronXL提供免費試用,確保滿足各類專案需求的靈活性和擴展性。
常見問題
我應該如何開始用C#操作Excel範圍?
要開始在C#中操作Excel範圍,請使用NuGet套件管理器安裝IronXL程式庫,命令為:Install-Package IronXL.Excel。然後,您可以開始載入Excel工作簿並使用IronXL的完整API操作範圍。
我如何使用IronXL載入Excel工作簿?
您可以在IronXL中使用WorkBook.Load方法載入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。




