Passer au contenu du pied de page
UTILISATION D'IRONXL

Comment convertir un fichier Excel en XML en C#

Microsoft Excel is a widely used multifunctional spreadsheet application renowned for its effectiveness in organizing, analyzing, and visualizing data. It works similarly to a grid where users may enter various types of input, such as text, numbers, dates, and formulas into individual cells, and the data is arranged into rows and columns for easy management. Its robust formula and function calculation capabilities enable users to perform a wide range of logical, statistical, and mathematical tasks.

Excel offers tools for managing and evaluating data as well as for producing graphs and charts that visually represent the data. It facilitates collaborative efforts by allowing several users to edit and share files simultaneously. It can be customized and automated with the use of macros, VBA, and add-ins due to its adaptability to a range of user demands across sectors. The Excel Workbook class is used in a variety of fields, including banking, education, research, and business analytics. It is an essential tool for organizing, evaluating, and using data to inform choices. In this article, we are going to learn how to convert Excel to XML in C#.

Convert Excel Files (XLS) to XML Format in C#

  1. Create a Console project in Visual Studio.
  2. Install the IronXL library.
  3. Initialize the necessary object of the IronXL.
  4. Create a new Excel file (XLS or XLSX) or load the Excel file into the created object.
  5. Use the SaveAsXml method within the XMLSaveOptions class to convert the loaded file into XML.
  6. Dispose of the IronXL objects.
using IronXL;

class Program
{
    static void Main()
    {
        // Step 2: Install IronXL library

        // Step 3: Initialize IronXL object
        WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);

        // Step 4: Create or load Excel file
        // Create a new Excel file
        WorkSheet worksheet = workbook.CreateWorkSheet("Sheet1");
        worksheet["A1"].Value = "Hello";
        worksheet["B1"].Value = "World";

        // Or load an existing Excel file
        workbook = WorkBook.Load("path_to_excel_file.xlsx");

        // Step 5: Convert Excel to XML
        XMLSaveOptions saveOptions = new XMLSaveOptions();
        workbook.SaveAsXml("path_to_output_xml_file.xml", saveOptions);

        // Step 6: Dispose of the IronXL objects
        worksheet.Dispose();
        workbook.Dispose();
    }
}
using IronXL;

class Program
{
    static void Main()
    {
        // Step 2: Install IronXL library

        // Step 3: Initialize IronXL object
        WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);

        // Step 4: Create or load Excel file
        // Create a new Excel file
        WorkSheet worksheet = workbook.CreateWorkSheet("Sheet1");
        worksheet["A1"].Value = "Hello";
        worksheet["B1"].Value = "World";

        // Or load an existing Excel file
        workbook = WorkBook.Load("path_to_excel_file.xlsx");

        // Step 5: Convert Excel to XML
        XMLSaveOptions saveOptions = new XMLSaveOptions();
        workbook.SaveAsXml("path_to_output_xml_file.xml", saveOptions);

        // Step 6: Dispose of the IronXL objects
        worksheet.Dispose();
        workbook.Dispose();
    }
}
Imports IronXL

Friend Class Program
	Shared Sub Main()
		' Step 2: Install IronXL library

		' Step 3: Initialize IronXL object
		Dim workbook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)

		' Step 4: Create or load Excel file
		' Create a new Excel file
		Dim worksheet As WorkSheet = workbook.CreateWorkSheet("Sheet1")
		worksheet("A1").Value = "Hello"
		worksheet("B1").Value = "World"

		' Or load an existing Excel file
		workbook = WorkBook.Load("path_to_excel_file.xlsx")

		' Step 5: Convert Excel to XML
		Dim saveOptions As New XMLSaveOptions()
		workbook.SaveAsXml("path_to_output_xml_file.xml", saveOptions)

		' Step 6: Dispose of the IronXL objects
		worksheet.Dispose()
		workbook.Dispose()
	End Sub
End Class
$vbLabelText   $csharpLabel

In the above code, we first install the IronXL library. Then, we initialize the IronXL object and create or load the Excel file. Finally, we use the SaveAsXml method with the XMLSaveOptions class to convert the loaded file into XML. Don't forget to dispose of the IronXL objects after use.

What is IronXL

A powerful .NET framework Excel library called IronXL was created to facilitate dealing with Excel written in C#, VB.NET, and other .NET languages. It is compatible with XLS and XLSX file formats. With the use of this library, developers may write, read, edit, and produce Excel spreadsheets more quickly and simply. A vast array of tools and functions are also available.

The key features and properties of IronXL include:

  • Data handling: IronXL makes it easy to read, write, and manipulate data in Excel spreadsheets. A two-dimensional array may be used to obtain cell values, and formulas, computations, and data formatting are all possible.
  • Excel File Creation and Modification: Developers may add, remove, and manage worksheets in addition to creating new Excel files and modifying ones that already exist. Additionally, they can communicate with a variety of Excel components using DLL files.
  • Versatility and Compatibility: IronXL may be utilized in a range of application scenarios because of its cross-platform interoperability and it can be integrated with multiple .NET platforms, including Xamarin, .NET Core, and .NET Framework.
  • Support for Both Legacy and Modern Excel Formats: It supports both the older XLS Excel format and the more modern XLSX Excel format. It can handle more recent XML-based formats (XLSX, from Excel 2007) as well as older Excel file formats (XLS, from Excel 97–2003).
  • Usefulness: By offering a straightforward API with easily understood attributes and functions, the library increases the accessibility of Excel-related activities for developers with varying degrees of experience.
  • Data Extraction and Export: IronXL facilitates the extraction of data from Excel files and the export of Excel data to several formats such as XML, new DataTable, and plain text, making it simple to interface with databases and other systems.
  • Support and Documentation: IronXL provides an abundance of tutorials, documentation, and support to assist developers in using its library for Excel-based activities.
  • Automation and Efficiency: By automating Excel procedures, IronXL enables users to build data-driven, efficient apps, increase productivity, and spend less time on manual labor.
  • Integration and Customization: It makes it easier to create personalized reports and data-driven solutions by exporting Excel data choices into a variety of formats. It also works well with databases and other systems.

Finance, data analysis, reporting, business intelligence, and software development are just a few of the several sectors that utilize IronXL. Combining data manipulation with Excel integration enables programmers to work with Excel files and produce reliable solutions. To learn more, go to this link.

Create a New Visual Studio Project

Setting up a Visual Studio Console project is easy. Follow these steps to create a Console application:

  1. Launch Visual Studio. Ensure that Visual Studio is installed on your computer.
  2. Create a new project: Select File > New > Project.

    How to Convert An Excel File to XML in C#: Figure 1 - New Project

  3. Choose your preferred programming language (e.g., C#) from the left side of the "Create a new project" box.
  4. From the list of available project templates, select the "Console App" or "Console App (.NET Core)" template.
  5. Provide a name for your project in the "Name" field.

    How to Convert An Excel File to XML in C#: Figure 2 - Project Configuration

  6. Choose the location to store your project.
  7. Click "Create" to start working on your new Console application project.

    How to Convert An Excel File to XML in C#: Figure 3 - Target Framework

Installing IronXL Library

To install the IronXL library, follow these steps:

  1. Install the IronXL library as it is required for the next steps. Use the following command in the NuGet Package Manager Console:

    Install-Package IronXL
    Install-Package IronXL
    SHELL

    How to Convert An Excel File to XML in C#: Figure 4 - Install IronXL

  2. Another approach is to use the NuGet Package Manager to search for the package "IronXL". Choose the appropriate NuGet package for IronXL from the search results.

    How to Convert An Excel File to XML in C#: Figure 5 - IronXL

Convert Excel File to XML in C#

You can save data from an Excel file into an XML file format using IronXL's SaveAsXml function.

Here's an example of how to use the SaveAsXml function in C# with IronXL:

using IronXL;

class Program
{
    static void Main(string[] args)
    {
        // Specify the path to your existing Excel file
        string excelFilePath = "path_to_excel_file.xlsx";
        // Specify the path to where the resulting XML file should be saved
        string xmlFilePath = "path_to_output_xml_file.xml";

        // Load Excel file using IronXL
        WorkBook workbook = WorkBook.Load(excelFilePath);

        // Save Excel data as XML
        workbook.SaveAsXml(xmlFilePath);

        Console.WriteLine("Excel data saved as XML successfully at: " + xmlFilePath);
    }
}
using IronXL;

class Program
{
    static void Main(string[] args)
    {
        // Specify the path to your existing Excel file
        string excelFilePath = "path_to_excel_file.xlsx";
        // Specify the path to where the resulting XML file should be saved
        string xmlFilePath = "path_to_output_xml_file.xml";

        // Load Excel file using IronXL
        WorkBook workbook = WorkBook.Load(excelFilePath);

        // Save Excel data as XML
        workbook.SaveAsXml(xmlFilePath);

        Console.WriteLine("Excel data saved as XML successfully at: " + xmlFilePath);
    }
}
Imports IronXL

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Specify the path to your existing Excel file
		Dim excelFilePath As String = "path_to_excel_file.xlsx"
		' Specify the path to where the resulting XML file should be saved
		Dim xmlFilePath As String = "path_to_output_xml_file.xml"

		' Load Excel file using IronXL
		Dim workbook As WorkBook = WorkBook.Load(excelFilePath)

		' Save Excel data as XML
		workbook.SaveAsXml(xmlFilePath)

		Console.WriteLine("Excel data saved as XML successfully at: " & xmlFilePath)
	End Sub
End Class
$vbLabelText   $csharpLabel

To save the resulting XML file, replace "path_to_output_xml_file.xml" with the appropriate location and "path_to_excel_file.xlsx" with the path to your actual Excel file.

This code sample loads an Excel file and uses the SaveAsXml function provided by IronXL to convert the Excel file data into XML format without manually looping through rows and columns to structure the XML. This method internally converts the Excel data to XML format and then saves it to the specified XML file.

Make sure you have the necessary permissions to write to the directory when saving the XML file. The content and layout of the original Excel file may influence the type and structure of the resulting XML.

Input file:

How to Convert An Excel File to XML in C#: Figure 6 - Excel Input

Result:

How to Convert An Excel File to XML in C#: Figure 7 - XML Output

To learn more about the code, refer to the code example here.

Conclusion

An easy and efficient way to export data from an Excel file to XML format is by using IronXL's SaveAsXml function. This method eliminates the need for manual iteration through rows and cells when converting Excel data into XML format. IronXL is a .NET library that provides this functionality.

By utilizing IronXL's SaveAsXml function in C#, users can easily and quickly convert Excel data to XML format. IronXL offers a free Community Edition with limitations for non-commercial use. Paid versions of IronXL are available through subscription or perpetual-based licensing models, starting at $799. These paid versions offer enhanced features, support, and complete functionality. For the most up-to-date information on licensing, please refer to the IronXL website. To learn more about Iron Software products, visit this page.

Questions Fréquemment Posées

Comment puis-je convertir un fichier Excel en XML en C#?

Vous pouvez convertir un fichier Excel en XML en C# en utilisant la bibliothèque IronXL. Tout d'abord, configurez un projet de console Visual Studio et installez IronXL via NuGet. Ensuite, chargez ou créez votre fichier Excel et utilisez la méthode SaveAsXml dans la classe XMLSaveOptions pour effectuer la conversion.

Quels sont les avantages d'utiliser IronXL pour la conversion Excel en XML ?

IronXL offre une API simple qui simplifie le processus de conversion des fichiers Excel en XML. Il gère la conversion en interne, permettant une intégration facile avec les applications .NET sans avoir besoin d'une itération manuelle des données.

IronXL est-il compatible avec les formats XLS et XLSX pour la conversion ?

Oui, IronXL est compatible avec les formats de fichiers XLS et XLSX, offrant une polyvalence pour diverses tâches de manipulation et de conversion de fichiers Excel.

Quelles sont les étapes d'installation d'IronXL dans un projet Visual Studio ?

Pour installer IronXL dans Visual Studio, vous pouvez utiliser la console du gestionnaire de packages NuGet avec la commande Install-Package IronXL, ou vous pouvez rechercher IronXL dans le gestionnaire de packages NuGet et l'installer directement à partir de là.

Comment puis-je m'assurer d'une suppression correcte des objets IronXL après utilisation ?

Après avoir utilisé les objets IronXL, assurez-vous de les supprimer correctement pour libérer les ressources. Cela peut être fait en appelant la méthode Dispose sur les objets une fois qu'ils ne sont plus nécessaires.

Quels langages de programmation sont compatibles avec IronXL?

IronXL peut être utilisé avec divers langages .NET, y compris C# et VB.NET, ce qui en fait un choix polyvalent pour les développeurs travaillant sur des applications nécessitant une intégration Excel.

Quelles options de licence sont disponibles pour IronXL ?

IronXL fournit une édition communautaire gratuite pour un usage non commercial avec des limitations, et pour des usages commerciaux, des versions payantes avec des fonctionnalités améliorées et un support sont disponibles via des abonnements ou des licences perpétuelles.

Comment IronXL facilite-t-il l'exportation de données d'Excel vers d'autres formats ?

IronXL permet l'extraction et l'exportation fluides de données à partir de fichiers Excel vers divers formats, tels que XML et texte brut, améliorant l'intégration avec les bases de données et d'autres systèmes.

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