在 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.Min() 和 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 表格中特定列的所有值。
透過 foreach 循環遍歷 columnValues,列中的每個值都使用 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 行)的單行中檢索所有值,從而能夠有效率地存取特定行的資料。 透過 foreach 循環遍歷 rowValues,行中的每個值都使用 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。


