使用 IRONXL 如何在 C# 中管理 Excel 范围 Curtis Chau 已更新:七月 28, 2025 Download IronXL NuGet 下载 DLL 下载 Start Free Trial Copy for LLMs Copy for LLMs Copy page as Markdown for LLMs Open in ChatGPT Ask ChatGPT about this page Open in Gemini Ask Gemini about this page Open in Grok Ask Grok about this page Open in Perplexity Ask Perplexity about this page Share Share on Facebook Share on X (Twitter) Share on LinkedIn Copy URL Email article Working with Excel files programmatically can significantly enhance the efficiency and automation capabilities of your C# applications. Whether you're generating reports, processing data, or creating complex spreadsheets dynamically, mastering the manipulation of Excel files is crucial. In this tutorial, we will focus on working with Excel ranges using IronXL. We'll cover how to write, read, and manipulate ranges within an Excel file. How to Read Excel Ranges in C# Install the IronXL library for handling Excel files. Load the workbook and specify the worksheet. Select the range of cells to read. Extract and read data from the specified range. What is IronXL? IronXL is a comprehensive library for C# that simplifies working with Excel files, offering a range of features for seamless integration and manipulation of spreadsheet data. 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. With support for calculations, formulas, and statistical analysis, IronXL empowers developers to efficiently handle Excel operations programmatically, making it an indispensable tool for automating data-centric tasks within C# applications. Getting Started with Excel Range of cells in C# First of all, we need to install the IronXL Library in our Application. Install the IronXL NuGet Package You can install IronXL via the NuGet Package Manager with the following command: Install-Package IronXL.Excel The above command will install IronXL with all its dependencies. Add Namespace Add the following namespace at the top of the Program.cs class, or wherever you want to use IronXL methods. using IronXL; using IronXL; Imports IronXL $vbLabelText $csharpLabel Load Excel Workbook The very first step is to load the Excel workbook. The following code will load the Excel workbook in our application. 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 The first line loads an existing Excel workbook from the file named "test_excel.xlsx". The second line retrieves the worksheet named "Sheet1" from the loaded workbook. I will be using the following Excel file throughout this tutorial. Reading Data from a range Now, let's read data from specified cell ranges. // 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 The first line selects a specific range address (A2 to G10) in the worksheet, allowing you to work with multiple Excel cells simultaneously. The foreach (var item in range) loop iterates over each cell within this cell range, enabling efficient data processing. By using Console.WriteLine(item);, the code prints each cell's value to the console, making it easy to review the contents of the range. This approach simplifies data handling and improves code readability. Use Excel Formulas in Range Let's select a specific range, and implement some Excel formulas. // 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 The code var range = sheet["F2:F42"]; selects a range of cells spanning from F2 to F42, facilitating statistical analysis of age data. Using range.Min() and range.Max(), it efficiently calculates the minimum and maximum age values within the specified range, aiding in demographic insights. Additionally, range.Avg() computes the average age, offering valuable statistical metrics for data interpretation. This approach simplifies data analysis tasks, providing quick access to essential statistical information for informed decision-making. Reading Data from a Single Cell Let's read data from a 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 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 The code var read_from_single_cell = sheet["B2"]; retrieves the value stored in cell B2 from the worksheet. Using this approach, you can easily access specific cell values within the Excel file. With Console.WriteLine($"The Value in Cell B2 is: {read_from_single_cell}");, the code prints the retrieved value of referencing cells to the console, facilitating data verification and debugging. This simplifies the process of retrieving and displaying individual cell values from Excel files. Reading Data from Entire column Let's Read Data from an entire column using Index. // 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 The code var columnValues = sheet.GetColumn(2); retrieves all values from the column located at index 2 (C column) in the worksheet. This allows you to efficiently access all values within a specific column of the Excel sheet. Through the foreach loop iterating over columnValues, each value in the column is printed to the console using Console.WriteLine(columnValue);. This approach facilitates processing and displaying columnar data from Excel files, streamlining data analysis tasks. Alternatively, we can also read data from a column using a Column Name instead of an index. Consider the following example: // 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 In this way, we can specify several columns. Reading Data from Entire row Let's Read data from the entire row by using row numbers. // 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 The code var rowValues = sheet.GetRow(1); retrieves all values from a single row located at index 1 (Row 2) in the worksheet, enabling efficient access to row-specific data. Through the foreach loop iterating over rowValues, each value in the row is printed to the console using Console.Write(rowValue + " ");. This approach simplifies the extraction and display of row data from Excel files, aiding in data analysis and reporting tasks. In this way, we can read values from multiple cells without range specification. Writing Data to Cell or a Range We can write data to both cell and range. First of all, we will write data to a range. // 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 The code var range = sheet["D2:D14"]; selects a range spanning from cell D2 to D14, enabling bulk data modification. By setting range.Value to "Prefer Not to Say", it efficiently updates the gender value for each cell within the specified range, minimizing repetitive tasks. The subsequent workbook.Save(); command ensures persistent storage of these changes, maintaining data consistency and integrity. This approach simplifies batch updates and ensures uniformity across multiple cells, enhancing data management efficiency. Now, Let's write data to a specific cell. // 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 The code sheet["B2"].Value = "John"; directly assigns the value "John" to cell B2 in the Excel worksheet, offering a concise and straightforward method for updating specific cell values. This approach streamlines the process of modifying individual cell contents, improving code readability and efficiency. Conclusion In conclusion, mastering Excel range operations in C# using IronXL significantly enhances the efficiency and automation capabilities of applications, facilitating tasks such as data processing, report generation, and dynamic spreadsheet creation. With IronXL's powerful features for reading, writing, and manipulating Excel files, developers can streamline data handling processes and leverage advanced functionalities like formulas, formatting, and statistical analysis. Additionally, IronXL offers a free trial, ensuring flexibility and scalability for various project requirements. 常见问题解答 如何开始在 C# 中操作 Excel 范围? 要在 C# 中开始操作 Excel 范围,请使用 NuGet Package Manager 安装 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 操作功能? IronXL 提供高级功能,如格式化、样式、条件格式化,以及支持计算和公式,增强了在 C# 应用程序中对 Excel 文件的操作能力。 在购买之前是否可以试用 IronXL? 是的,IronXL 提供免费试用版,允许开发人员探索其功能并确定其对项目的适用性,无需任何初始费用。 IronXL 如何增强 C# 应用程序的自动化功能? IronXL 通过使 Excel 文件的编程操作变得无缝连接,在 C# 应用程序中增强了自动化功能,这对于诸如数据处理、报告生成和动态电子表格创建等任务至关重要,无需安装 Microsoft Excel。 Curtis Chau 立即与工程团队聊天 技术作家 Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。 相关文章 已发布十月 27, 2025 如何在 C# 中创建 Excel 数据透视表 学习通过这个清晰的分步指南使用C# Interop和IronXL在Excel中创建数据透视表。 阅读更多 已发布十月 27, 2025 如何在C#中将DataGridView导出到包含列头的Excel 学习如何在将DataGridView数据导出到Excel时保留列头。使用IronXL库的C#逐步教程。 阅读更多 已发布十月 27, 2025 如何在.NET Core中使用CSV Reader与IronXL 学习通过实际示例有效地使用IronXL作为.NET Core的CSV读取器。 阅读更多 如何在 VB.NET 中将数据集转换为 Excel如何在 C# 中处理 Excel 文件
已发布十月 27, 2025 如何在C#中将DataGridView导出到包含列头的Excel 学习如何在将DataGridView数据导出到Excel时保留列头。使用IronXL库的C#逐步教程。 阅读更多