跳過到頁腳內容
使用 IRONXL

在 C# 中如何管理 Excel 範圍

以程式化方式處理Excel文件可以顯著提高您的C#應用程序的效率和自動化能力。 無論是生成報告、處理數據還是動態創建複雜電子表格,掌握對Excel文件的操作都是至關重要的。 在本教程中,我們將專注於使用IronXL進行Excel範圍的操作。 We'll cover how to write, read, and manipulate ranges within an Excel file.

如何在C#中讀取Excel範圍

  1. 安裝IronXL庫以處理Excel文件。
  2. 加載工作簿並指定工作頁。
  3. 選擇要讀取的單元格範圍。
  4. 從指定範圍中提取和讀取數據。

什麼是 IronXL?

IronXL是C#的一個綜合庫,簡化了Excel文件的操作,提供了從集成到操作電子表格數據的一系列功能。 Its capabilities include reading, writing, and modifying Excel files without requiring Microsoft Excel installation, enabling cross-platform compatibility.

IronXL facilitates the extraction of data from specific cells, ranges, or entire worksheets, along with advanced functionalities such as formatting, styling, and conditional formatting. 支持計算、公式和統計分析,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表特定列中的所有值。

通過columnValuesforeach循環,欄位中的每個值將被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設置為"Prefer Not to Say",它有效地更新指定範圍內每個單元格的性別值,從而減少重複任務。

隨後的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 Range

結論

總之,在C#中使用IronXL掌握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。

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