Passer au contenu du pied de page
UTILISATION D'IRONXL

Comment gérer les plages Excel en 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#

  1. Install the IronXL library for handling Excel files.
  2. Load the workbook and specify the worksheet.
  3. Select the range of cells to read.
  4. 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.

How to Manage Excel Ranges in C#: Figure 1

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.

How to Manage Excel Ranges in C#: Figure 2

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.

How to Manage Excel Ranges in C#: Figure 3

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.

How to Manage Excel Ranges in C#: Figure 4

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.

How to Manage Excel Ranges in C#: Figure 5

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.

How to Manage Excel Ranges in C#: Figure 6

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.

How to Manage Excel Ranges in C#: Figure 7 - C# Excel Range

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.

Questions Fréquemment Posées

Comment puis-je commencer à manipuler des plages Excel en C# ?

Pour commencer à manipuler des plages Excel en C#, installez la bibliothèque IronXL via le Gestionnaire de Paquets NuGet en utilisant la commande : Install-Package IronXL.Excel. Ensuite, vous pouvez commencer à charger des classeurs Excel et à travailler avec des plages en utilisant l'API complète d'IronXL.

Comment puis-je charger un classeur Excel en utilisant IronXL ?

Vous pouvez charger un classeur Excel dans IronXL avec la méthode WorkBook.Load, en passant le nom de fichier comme argument, par exemple : var workbook = WorkBook.Load('test_excel.xlsx');.

Quelles méthodes sont disponibles pour lire une plage spécifique de cellules dans IronXL ?

Dans IronXL, vous pouvez lire une plage spécifique de cellules en définissant la plage en utilisant une syntaxe comme sheet['A2:G10'] et en itérant dessus pour accéder à la valeur de chaque cellule.

Comment puis-je effectuer une analyse statistique sur des données dans une plage Excel ?

En utilisant IronXL, vous pouvez effectuer une analyse statistique en sélectionnant une plage et en appliquant des méthodes telles que range.Min(), range.Max(), et range.Avg() pour calculer respectivement les valeurs minimum, maximum et moyenne.

Quel est le processus pour écrire des données dans une cellule spécifique en utilisant IronXL ?

Pour écrire des données dans une cellule spécifique dans IronXL, assignez une valeur directement à la cellule, par exemple : sheet['B2'].Value = 'John';, puis enregistrez le classeur pour conserver les modifications.

Puis-je lire une colonne entière de données sans spécifier une plage dans IronXL ?

Oui, IronXL vous permet de lire une colonne entière en utilisant sheet.GetColumn(index) ou sheet.GetColumn('C'), vous permettant de récupérer des données soit à l'aide d'un index soit d'un nom de colonne.

Comment extraire des données d'une ligne entière en utilisant IronXL ?

Pour extraire des données d'une ligne entière dans IronXL, utilisez sheet.GetRow(index) et itérez sur les valeurs récupérées pour accéder aux données.

Quelles fonctionnalités avancées IronXL offre-t-il pour la manipulation d'Excel ?

IronXL offre des fonctions avancées telles que le formatage, le style, le formatage conditionnel et le support pour les calculs et formules, améliorant les capacités de manipulation des fichiers Excel dans les applications C#.

Est-il possible d'essayer IronXL avant de l'acheter ?

Oui, IronXL propose un essai gratuit, permettant aux développeurs d'explorer ses fonctionnalités et de déterminer son adéquation pour leurs projets sans aucun coût initial.

Comment IronXL peut-il améliorer l'automatisation dans les applications C# ?

IronXL améliore l'automatisation dans les applications C# en permettant une manipulation transparente des fichiers Excel par programmation, ce qui est essentiel pour des tâches telles que le traitement de données, la génération de rapports et la création dynamique de feuilles de calcul, le tout sans nécessiter l'installation de Microsoft Excel.

Jordi Bardia
Ingénieur logiciel
Jordi est le plus compétent en Python, C# et C++, et lorsqu'il ne met pas à profit ses compétences chez Iron Software, il programme des jeux. Partageant les responsabilités des tests de produit, du développement de produit et de la recherche, Jordi apporte une immense valeur à l'amé...
Lire la suite