Jak zarządzać zakresami w Excelu w języku C#
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.
Czym jest 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
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
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
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()))}")
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}")
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
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")
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
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()
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.
Teraz zapiszmy dane w określonej komórce.
// 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()
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. Takie podejście usprawnia proces modyfikacji zawartości poszczególnych komórek, poprawiając czytelność i wydajność kodu.

Wnioski
Podsumowując, opanowanie operacji na zakresach w Excelu w języku C# przy użyciu IronXL znacznie zwiększa wydajność i możliwości automatyzacji aplikacji, ułatwiając zadania takie jak przetwarzanie danych, generowanie raportów i dynamiczne tworzenie arkuszy kalkulacyjnych.
Dzięki zaawansowanym funkcjom IronXL do odczytu, zapisu i manipulacji plikami Excel programiści mogą usprawnić procesy przetwarzania danych i wykorzystać zaawansowane funkcje, takie jak formuły, formatowanie i analiza statystyczna. Ponadto IronXL oferuje bezpłatną wersję próbną, zapewniając elastyczność i skalowalność dostosowaną do różnych wymagań projektowych.
Często Zadawane Pytania
Jak zacząć manipulować zakresami w Excelu w języku C#?
Aby rozpocząć manipulowanie zakresami w Excelu w języku C#, zainstaluj bibliotekę IronXL za pomocą menedżera pakietów NuGet, używając polecenia: Install-Package IronXl.Excel. Następnie możesz rozpocząć ładowanie skoroszytów Excel i pracę z zakresami przy użyciu kompleksowego interfejsu API IronXL.
Jak załadować skoroszyt Excel za pomocą IronXL?
W programie IronXL można załadować skoroszyt Excel za pomocą metody WorkBook.Load, przekazując nazwę pliku jako argument, na przykład: var workbook = WorkBook.Load('test_excel.xlsx');.
Jakie metody są dostępne do odczytu określonego zakresu komórek w IronXL?
W IronXL można odczytać określony zakres komórek, definiując go za pomocą składni takiej jak sheet['A2:G10'] i iterując po nim, aby uzyskać dostęp do wartości każdej komórki.
Jak przeprowadzić analizę statystyczną danych w zakresie arkusza Excel?
Korzystając z IronXL, można przeprowadzić analizę statystyczną, zaznaczając zakres i stosując metody takie jak range.Min(), range.Max() oraz range.Avg(), aby obliczyć odpowiednio wartości minimalną, maksymalną i średnią.
Jak wygląda proces zapisywania danych w konkretnej komórce przy użyciu IronXL?
Aby zapisać dane w określonej komórce w IronXL, należy przypisać wartość bezpośrednio do komórki, na przykład: sheet['B2'].Value = 'John';, a następnie zapisać skoroszyt, aby zachować zmiany.
Czy w IronXL mogę odczytać całą kolumnę danych bez określania zakresu?
Tak, IronXL pozwala odczytać całą kolumnę za pomocą sheet.GetColumn(index) lub sheet.GetColumn('C'), umożliwiając pobieranie danych przy użyciu indeksu lub nazwy kolumny.
Jak wyodrębnić dane z całego wiersza za pomocą IronXL?
Aby wyodrębnić dane z całego wiersza w IronXL, należy użyć funkcji sheet.GetRow(index) i iterować nad pobranymi wartościami, aby uzyskać dostęp do danych.
Jakie zaawansowane funkcje oferuje IronXL do obsługi arkuszy kalkulacyjnych Excel?
IronXL oferuje zaawansowane funkcje, takie jak formatowanie, stylizacja, formatowanie warunkowe oraz obsługę obliczeń i formuł, zwiększając możliwości manipulacji plikami Excel w aplikacjach C#.
Czy można wypróbować IronXL przed zakupem?
Tak, IronXL oferuje bezpłatną wersję próbną, która pozwala programistom zapoznać się z jego funkcjonalnościami i ocenić jego przydatność do swoich projektów bez ponoszenia żadnych początkowych kosztów.
W jaki sposób IronXL może usprawnić automatyzację w aplikacjach C#?
IronXL usprawnia automatyzację w aplikacjach C#, umożliwiając płynną manipulację plikami Excel za pomocą kodu, co jest niezbędne do zadań takich jak przetwarzanie danych, generowanie raportów i dynamiczne tworzenie arkuszy kalkulacyjnych, a wszystko to bez konieczności instalowania programu Microsoft Excel.




