Passer au contenu du pied de page
UTILISATION D'IRONXL

Travailler avec des fichiers Excel sans Microsoft Office en C#

Introduction to IronXL

IronXL library serves as an alternative to traditional Excel Interop in C#, offering a more streamlined and efficient approach to handling Excel files.

It is a useful Excel API for developers managing Microsoft Excel data in .NET applications, functioning independently of Microsoft Office. It offers a straightforward way to manage Excel files in various formats like XLSX, XLS, and CSV.

Why Choose IronXL?

The absence of a requirement for MS Office installation on the server makes IronXL an optimal solution in various server environments.

This makes it a go-to solution for server environments where installing Microsoft Office is not feasible due to licensing or server performance constraints.

Key Features of IronXL

The key features of IronXL are as follows:

  • Reading and Writing Excel Files: IronXL can create and manipulate Excel files. It supports both classic XLS and modern XLSX file formats, ensuring compatibility with different versions of Excel.
  • Exporting Data: IronXL can export data to and from Excel files to other formats efficiently like XML files, CSV, and other formats.
  • Support for .NET Core and Framework: IronXL works seamlessly with both .NET Core and .NET Framework, making it a versatile choice for various development environments.
  • Ease of Use: With IronXL, developers can perform complex Excel operations with minimal lines of code, enhancing productivity and efficiency.

Installation and Setup

To start using IronXL, you need to install the NuGet package. Here's how you can do it:

Via NuGet Package Manager: Search for IronXL in the NuGet Packages Manager and install it.

C# Excel Library Without Office (Beginner Tutorial): Figure 1

Using Package Manager Console: Run the command Install-Package IronXL.Excel in the Package Manager Console in Visual Studio.

Working with IronXL

IronXL empowers C# developers with the ability to interact with Excel files efficiently. This section will delve into the various operations you can perform with IronXL, providing detailed guidance and code examples.

Creating a New Excel File

Creating a new Excel file is a common task in data manipulation and reporting. With IronXL, you can effortlessly create Excel files with a few lines of code, add worksheets, and populate them with data.

The following code shows how we can create an Excel file using IronXL:

using IronXL;

// Initialize a new Workbook
var workbook = new WorkBook();
// Add a new Worksheet named "Sales Data"
var worksheet = workbook.CreateWorkSheet("Sales Data");

// Populate the Worksheet with data
worksheet["A1"].Value = "Month";
worksheet["B1"].Value = "Sales";
worksheet["A2"].Value = "January";
worksheet["B2"].Value = 5000;
worksheet["A3"].Value = "February";
worksheet["B3"].Value = 6000;

// Save the Workbook as an Excel file
workbook.SaveAs("SalesReport.xlsx");
using IronXL;

// Initialize a new Workbook
var workbook = new WorkBook();
// Add a new Worksheet named "Sales Data"
var worksheet = workbook.CreateWorkSheet("Sales Data");

// Populate the Worksheet with data
worksheet["A1"].Value = "Month";
worksheet["B1"].Value = "Sales";
worksheet["A2"].Value = "January";
worksheet["B2"].Value = 5000;
worksheet["A3"].Value = "February";
worksheet["B3"].Value = 6000;

// Save the Workbook as an Excel file
workbook.SaveAs("SalesReport.xlsx");
Imports IronXL

' Initialize a new Workbook
Private workbook = New WorkBook()
' Add a new Worksheet named "Sales Data"
Private worksheet = workbook.CreateWorkSheet("Sales Data")

' Populate the Worksheet with data
Private worksheet("A1").Value = "Month"
Private worksheet("B1").Value = "Sales"
Private worksheet("A2").Value = "January"
Private worksheet("B2").Value = 5000
Private worksheet("A3").Value = "February"
Private worksheet("B3").Value = 6000

' Save the Workbook as an Excel file
workbook.SaveAs("SalesReport.xlsx")
$vbLabelText   $csharpLabel

C# Excel Library Without Office (Beginner Tutorial): Figure 2

This code creates a workbook, adds a worksheet, and populates it with sales data before saving it as an Excel file.

IronXL supports standard Excel notation, enabling developers to reference cells like 'A1' for reading and manipulating data.

Reading Excel Files

Reading and extracting information from Excel files is crucial for data processing applications. IronXL allows you to open existing Excel files and read their content without Excel interop.

Here’s a code example:

using IronXL;

// Load an existing Excel file
var workbook = WorkBook.Load("FinancialData.xlsx");

// Access a specific worksheet by name
var worksheet = workbook.GetWorkSheet("Quarterly Report");

// Read values from specific cells
string quarter = worksheet["A2"].StringValue;
double revenue = worksheet["B2"].DoubleValue;
double expenses = worksheet["C2"].DoubleValue;

// You can also iterate over rows and columns if needed
foreach (var row in worksheet.Rows)
{
    foreach (var cell in row)
    {
        Console.WriteLine(cell.Value);
    }
}
using IronXL;

// Load an existing Excel file
var workbook = WorkBook.Load("FinancialData.xlsx");

// Access a specific worksheet by name
var worksheet = workbook.GetWorkSheet("Quarterly Report");

// Read values from specific cells
string quarter = worksheet["A2"].StringValue;
double revenue = worksheet["B2"].DoubleValue;
double expenses = worksheet["C2"].DoubleValue;

// You can also iterate over rows and columns if needed
foreach (var row in worksheet.Rows)
{
    foreach (var cell in row)
    {
        Console.WriteLine(cell.Value);
    }
}
Imports IronXL

' Load an existing Excel file
Private workbook = WorkBook.Load("FinancialData.xlsx")

' Access a specific worksheet by name
Private worksheet = workbook.GetWorkSheet("Quarterly Report")

' Read values from specific cells
Private quarter As String = worksheet("A2").StringValue
Private revenue As Double = worksheet("B2").DoubleValue
Private expenses As Double = worksheet("C2").DoubleValue

' You can also iterate over rows and columns if needed
For Each row In worksheet.Rows
	For Each cell In row
		Console.WriteLine(cell.Value)
	Next cell
Next row
$vbLabelText   $csharpLabel

This code demonstrates how to load an Excel file, access a specific worksheet, and read values from cells, including iterating over rows and columns.

Writing Data to Excel Files

Modifying Excel files is a frequent requirement. IronXL allows you to write and update data in Excel files with ease.

The following example illustrates adding and updating data in an Excel file:

using IronXL;

// Load an existing Excel file
var workbook = WorkBook.Load("EmployeeData.xlsx");
var worksheet = workbook.DefaultWorkSheet;

// Adding new data to cells
worksheet["A4"].Value = "John Doe";
worksheet["B4"].Value = "Sales";
worksheet["C4"].Value = 45000;

// Updating existing data
worksheet["C2"].Value = 50000; // Update salary of an existing employee

// Save the changes to a new file
workbook.SaveAs("UpdatedEmployeeData.xlsx");
using IronXL;

// Load an existing Excel file
var workbook = WorkBook.Load("EmployeeData.xlsx");
var worksheet = workbook.DefaultWorkSheet;

// Adding new data to cells
worksheet["A4"].Value = "John Doe";
worksheet["B4"].Value = "Sales";
worksheet["C4"].Value = 45000;

// Updating existing data
worksheet["C2"].Value = 50000; // Update salary of an existing employee

// Save the changes to a new file
workbook.SaveAs("UpdatedEmployeeData.xlsx");
Imports IronXL

' Load an existing Excel file
Private workbook = WorkBook.Load("EmployeeData.xlsx")
Private worksheet = workbook.DefaultWorkSheet

' Adding new data to cells
Private worksheet("A4").Value = "John Doe"
Private worksheet("B4").Value = "Sales"
Private worksheet("C4").Value = 45000

' Updating existing data
Private worksheet("C2").Value = 50000 ' Update salary of an existing employee

' Save the changes to a new file
workbook.SaveAs("UpdatedEmployeeData.xlsx")
$vbLabelText   $csharpLabel

In this example, new data is added to an Excel file, and existing data is updated, showcasing the flexibility of IronXL in data manipulation.

C# Excel Library Without Office (Beginner Tutorial): Figure 3

Exporting Excel Data

Exporting data from Excel files to other formats is often required for data analysis and reporting. IronXL simplifies this process.

Here’s how you can export data from an Excel file to a CSV format:

using IronXL;

// Load the Excel file
var workbook = WorkBook.Load("ProjectData.xlsx");

// Export the entire Workbook or a specific Worksheet to CSV
workbook.SaveAsCsv("ProjectData.csv");

// You can also export to other formats like JSON
workbook.SaveAsJson("ProjectData.json");
using IronXL;

// Load the Excel file
var workbook = WorkBook.Load("ProjectData.xlsx");

// Export the entire Workbook or a specific Worksheet to CSV
workbook.SaveAsCsv("ProjectData.csv");

// You can also export to other formats like JSON
workbook.SaveAsJson("ProjectData.json");
Imports IronXL

' Load the Excel file
Private workbook = WorkBook.Load("ProjectData.xlsx")

' Export the entire Workbook or a specific Worksheet to CSV
workbook.SaveAsCsv("ProjectData.csv")

' You can also export to other formats like JSON
workbook.SaveAsJson("ProjectData.json")
$vbLabelText   $csharpLabel

This code snippet demonstrates the conversion of Excel files to CSV and JSON formats, highlighting IronXL's versatility in handling different file formats.

Advanced Features of IronXL

IronXL isn't just about basic Excel operations; it comes packed with advanced features that cater to complex data manipulation and formatting needs. Let's explore some of these capabilities in more detail.

Working with Data Tables

Converting between Excel sheets and .NET data tables is a feature that enhances the flexibility of data handling in IronXL. This functionality is particularly useful for scenarios involving bulk data operations or when interfacing with databases.

using IronXL;
using System.Data;

// Load an existing Excel file
var workbook = WorkBook.Load("EmployeeRecords.xlsx");
var worksheet = workbook.DefaultWorkSheet;

// Convert the Worksheet to a DataTable
DataTable dataTable = worksheet.ToDataTable(true);
using IronXL;
using System.Data;

// Load an existing Excel file
var workbook = WorkBook.Load("EmployeeRecords.xlsx");
var worksheet = workbook.DefaultWorkSheet;

// Convert the Worksheet to a DataTable
DataTable dataTable = worksheet.ToDataTable(true);
Imports IronXL
Imports System.Data

' Load an existing Excel file
Private workbook = WorkBook.Load("EmployeeRecords.xlsx")
Private worksheet = workbook.DefaultWorkSheet

' Convert the Worksheet to a DataTable
Private dataTable As DataTable = worksheet.ToDataTable(True)
$vbLabelText   $csharpLabel

Performance Optimization for Large Excel Files

Handling large Excel files efficiently is a key feature of IronXL, making it suitable for enterprise-level applications dealing with substantial amounts of data.

IronXL is designed to minimize memory usage and optimize performance when working with large Excel files.

It achieves this through efficient data handling algorithms and by allowing selective reading of worksheets and cells, thereby reducing the load on system resources.

Handling Excel File Formats

IronXL supports various Excel file formats, ensuring compatibility across different versions of Excel and other spreadsheet software.

using IronXL;

// Creating a workbook
var workbook = new WorkBook();

// You can save the Workbook in various formats
workbook.SaveAs("ExcelDocument.xlsx"); // XLSX format
workbook.SaveAs("ExcelDocument.xls");  // XLS format
workbook.SaveAsCsv("ExcelDocument.csv");  // CSV format
using IronXL;

// Creating a workbook
var workbook = new WorkBook();

// You can save the Workbook in various formats
workbook.SaveAs("ExcelDocument.xlsx"); // XLSX format
workbook.SaveAs("ExcelDocument.xls");  // XLS format
workbook.SaveAsCsv("ExcelDocument.csv");  // CSV format
Imports IronXL

' Creating a workbook
Private workbook = New WorkBook()

' You can save the Workbook in various formats
workbook.SaveAs("ExcelDocument.xlsx") ' XLSX format
workbook.SaveAs("ExcelDocument.xls") ' XLS format
workbook.SaveAsCsv("ExcelDocument.csv") ' CSV format
$vbLabelText   $csharpLabel

This example shows how IronXL can create and save documents in XLSX, XLS, and CSV formats, providing flexibility in how data is stored and shared.

Conclusion

C# Excel Library Without Office (Beginner Tutorial): Figure 4

IronXL is a powerful C# library for working with Excel files without the need for Microsoft Office. Its ability to read, write, and export Excel files, combined with its ease of use and support for both .NET Core and .NET Framework, makes it an excellent choice for developers dealing with Excel data in their applications.

Whether you are creating new Excel documents, processing existing files, or exporting data to different formats, IronXL offers a robust and efficient solution.

For more detailed documentation, code examples, and support, visit the IronXL official website or check out their GitHub repository. With IronXL, managing Excel files in C# becomes a streamlined and hassle-free process.

IronXL offers a free trial for users to explore its features and capabilities before making a purchase. This trial period allows developers to test the library in their environments, ensuring it meets their specific needs for Excel file manipulation in .NET applications.

After the trial, licenses for IronXL start at $799, providing full access to all its advanced features and functionalities.

Questions Fréquemment Posées

Comment fonctionne IronXL sans Microsoft Office ?

IronXL est conçu pour gérer les fichiers Excel dans les applications .NET sans le besoin de Microsoft Office. Il fournit une API simplifiée qui permet aux développeurs d'effectuer des opérations Excel sans dépendre de l'Interop Office.

Quels sont les avantages d'utiliser IronXL pour les opérations Excel dans des environnements serveur ?

IronXL est idéal pour les environnements serveur car il élimine le besoin de Microsoft Office, évitant ainsi les problèmes de licence ou de performance. Il permet une manipulation fluide des fichiers Excel dans des environnements où Office ne peut être installé.

Comment puis-je lire et écrire des fichiers Excel avec IronXL ?

Avec IronXL, vous pouvez lire et écrire des fichiers Excel en initialisant un nouveau Workbook, en accédant aux objets Worksheet, et en utilisant des méthodes pour lire ou écrire des données dans les cellules Excel.

Quels formats de fichiers Excel sont supportés par IronXL ?

IronXL prend en charge une variété de formats de fichiers Excel, y compris XLSX, XLS, et CSV. Il permet également d'exporter des données vers des formats comme XML et JSON, améliorant l'interopérabilité des données.

Comment puis-je installer IronXL dans mon projet .NET ?

Vous pouvez installer IronXL via le gestionnaire de packages NuGet en recherchant 'IronXL' ou en exécutant la commande Install-Package IronXL.Excel dans la console du gestionnaire de packages.

IronXL est-il compatible avec .NET Core et .NET Framework ?

Oui, IronXL est compatible avec à la fois .NET Core et .NET Framework, ce qui en fait une option flexible pour divers environnements de développement.

IronXL peut-il gérer de grands fichiers Excel efficacement?

IronXL est optimisé pour gérer efficacement de grands fichiers Excel en minimisant l'utilisation de mémoire et en fournissant des méthodes pour la lecture et l'écriture sélectives de données.

Comment puis-je exporter des données Excel vers d'autres formats en utilisant IronXL ?

IronXL vous permet d'exporter des données Excel vers des formats comme CSV et JSON, ce qui facilite l'analyse et le reporting des données sur différentes plateformes.

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

IronXL offre des fonctionnalités avancées comme la conversion de feuilles Excel en tables de données .NET et l'optimisation des performances pour de grands ensembles de données avec des algorithmes de gestion efficaces.

Y a-t-il un essai gratuit disponible pour IronXL ?

Oui, IronXL propose une version d'essai gratuite pour les nouveaux utilisateurs. Cela vous permet d'explorer ses fonctionnalités avant de décider d'acheter une licence pour un accès complet.

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