跳過到頁腳內容
使用 IRONXL

在 C# 中如何管理 Excel 範圍

透過程式處理Excel 檔案可以顯著提高 C# 應用程式的效率和自動化功能。 無論您是產生報表、處理資料還是動態建立複雜的電子表格,掌握 Excel 檔案的操作都至關重要。 在本教程中,我們將重點放在如何使用IronXL處理 Excel 區域。 我們將介紹如何在 Excel 檔案中寫入讀取操作區域

如何在 C# 中讀取 Excel 區域

  1. 安裝 IronXL 庫以處理 Excel 檔案。
  2. 載入工作簿並指定工作表。
  3. 選擇要讀取的儲存格範圍。
  4. 從指定範圍內提取和讀取資料。

IronXL是什麼?

IronXL是一個全面的 C# 庫,它簡化了 Excel 檔案的操作,提供了一系列功能,可實現電子表格資料的無縫整合和操作。 它具備讀取寫入修改Excel 檔案的功能,無需安裝 Microsoft Excel,從而實現跨平台相容性。

IronXL 可輕鬆從特定儲存格區域或整個工作表中提取數據,並提供格式設定樣式設定條件格式設定等進階功能。 IronXL 支援計算、公式和統計分析,使開發人員能夠以程式設計方式有效地處理 Excel 操作,使其成為在 C# 應用程式中自動化以資料為中心的任務的不可或缺的工具。

C# 中 Excel 儲存格區域的入門

首先,我們需要在應用程式中安裝 IronXL 庫。

安裝 IronXL NuGet 套件

您可以使用以下命令透過 NuGet 套件管理器安裝 IronXL:

Install-Package IronXL.Excel

上述指令將安裝 IronXL 及其所有相依性。

如何在 C# 中管理 Excel 區域:圖 1

新增命名空間

在 Program.cs 類別的頂部,或任何你想使用 IronXL 方法的地方,加入以下命名空間。

using IronXL;
using IronXL;
Imports IronXL
$vbLabelText   $csharpLabel

載入 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
$vbLabelText   $csharpLabel

第一行程式碼從名為"test_excel.xlsx"的檔案載入一個現有的Excel工作簿。 第二行從已載入的工作簿中擷取名為"Sheet1"的工作表。

在本教程中,我將使用以下Excel檔案。

如何在 C# 中管理 Excel 區域:圖 2

從一系列數據中讀取數據

現在,讓我們讀取指定單元格範圍內的資料。

// 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
$vbLabelText   $csharpLabel

第一行選擇工作表中的特定範圍位址(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()))}")
$vbLabelText   $csharpLabel

代碼var range = sheet["F2:F42"];選擇從 F2 到 F42 的儲存格區域,以便對年齡資料進行統計分析。 使用range.Min()range.Max() ,可以有效率地計算指定範圍內的最小和最大年齡值,有助於人口統計分析。

此外, range.Avg()可以計算平均年齡,為數據解釋提供有價值的統計指標。 這種方法簡化了數據分析任務,使用戶能夠快速獲取必要的統計信息,從而做出明智的決策。

如何在 C# 中管理 Excel 區域:圖 3

從單一細胞讀取數據

讓我們讀取單一細胞中的數據。

// 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}")
$vbLabelText   $csharpLabel

程式碼var read_from_single_cell = sheet["B2"];從工作表擷取儲存在儲存格 B2 中的值。 使用此方法,您可以輕鬆存取 Excel 檔案中的特定儲存格值。

使用Console.WriteLine($"The Value in Cell B2 is: {read_from_single_cell}"); ,程式碼會將引用儲存格的擷取值列印到控制台,以便於資料驗證和除錯。 這簡化了從 Excel 檔案中檢索和顯示單一儲存格值的過程。

如何在 C# 中管理 Excel 區域:圖 4

讀取整列數據

讓我們使用索引讀取整列資料。

// 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
$vbLabelText   $csharpLabel

代碼var columnValues = sheet.GetColumn(2);檢索工作表中索引為 2(C 列)的欄位中的所有值。 這樣可以有效率地存取 Excel 表格中特定列的所有值。

透過foreach循環遍歷columnValues ,使用Console.WriteLine(columnValue); 這種方法便於處理和顯示 Excel 文件中的列式數據,簡化數據分析任務。

如何在 C# 中管理 Excel 區域:圖 5

或者,我們也可以使用列名而不是索引從列中讀取資料。 請考慮以下範例:

// 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")
$vbLabelText   $csharpLabel

這樣我們就可以指定多列了。

讀取整行數據

讓我們透過行號讀取整行資料。

// 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
$vbLabelText   $csharpLabel

程式碼var rowValues = sheet.GetRow(1);從工作表中索引為 1(第 2 行)的單行中檢索所有值,從而可以有效地存取特定行的資料。 透過foreach迴圈遍歷rowValues ,使用Console.Write(rowValue + " ");將行中的每個值列印到控制台。

這種方法簡化了從 Excel 文件中提取和顯示行資料的過程,有助於資料分析和報告任務。 這樣,我們就可以在不指定範圍的情況下讀取多個單元格的值。

如何在 C# 中管理 Excel 區域:圖 6

將資料寫入儲存格或範圍

我們可以將資料寫入儲存格和區域。 首先,我們將資料寫入一個範圍。

// 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()
$vbLabelText   $csharpLabel

代碼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()
$vbLabelText   $csharpLabel

程式碼sheet["B2"].Value = "John";直接將值"John"賦值給 Excel 工作表中的儲存格 B2,提供了一種簡潔直接的方法來更新特定儲存格的值。 這種方法簡化了修改單一儲存格內容的過程,提高了程式碼的可讀性和效率。

如何在 C# 中管理 Excel 區域:圖 7 - C# Excel 區域

結論

總而言之,掌握使用 IronXL 在 C# 中進行 Excel 區域操作可以顯著提高應用程式的效率和自動化能力,從而簡化資料處理、報表產生和動態電子表格建立等任務。

IronXL 具有強大的 Excel 檔案讀取、寫入和操作功能,開發人員可以簡化資料處理流程,並利用公式、格式設定和統計分析等進階功能。 此外,IronXL 還提供免費試用,確保其能夠靈活且可擴展地滿足各種專案需求。

常見問題解答

如何開始使用 C# 操作 Excel 範圍?

若要開始在 C# 中操作 Excel 範圍,請使用下列指令透過 NuGet 套件管理員安裝 IronXL 函式庫:Install-Package IronXL.Excel。然後,您就可以開始載入 Excel 工作簿,並使用 IronXL 的全面 API 來處理範圍。

如何使用 IronXL 載入 Excel 工作簿?

您可以使用 WorkBook.Load 方法在 IronXL 中載入 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 提供哪些 Excel 操作的進階功能?

IronXL.Excel 提供格式化、樣式化、條件格式化等進階功能,並支援計算和公式,增強 C# 應用程式內 Excel 檔案的操作能力。

是否可以在購買之前試用 IronXL?

是的,IronXL 提供免費試用,讓開發人員可以探索其功能,並確定其是否適合他們的專案,而無需任何初始成本。

IronXL 如何增強 C# 應用程式的自動化?

IronXL 可透過程式化的方式對 Excel 檔案進行無縫操作,增強 C# 應用程式的自動化功能,這對於資料處理、報表產生和動態試算表建立等任務而言是不可或缺的,而這一切都不需要安裝 Microsoft Excel。

Jordi Bardia
軟體工程師
Jordi 在 Python、C# 和 C++ 上最得心應手,當他不在 Iron Software 展現技術時,便在做遊戲編程。在分担产品测测试,产品开发和研究的责任时,Jordi 为持续的产品改进增值。他说这种多样化的经验使他受到挑战并保持参与, 而这也是他与 Iron Software 中工作一大乐趣。Jordi 在佛罗里达州迈阿密长大,曾在佛罗里达大学学习计算机科学和统计学。