Saltar al pie de página
USANDO IRONXL

Cómo convertir un archivo de Excel a 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.

Preguntas Frecuentes

¿Cómo puedo convertir un archivo Excel a XML en C#?

Puedes convertir un archivo Excel a XML en C# usando la biblioteca IronXL. Primero, configura un proyecto de consola de Visual Studio e instala IronXL a través de NuGet. Luego, carga o crea tu archivo Excel y utiliza el método SaveAsXml dentro de la clase XMLSaveOptions para realizar la conversión.

¿Cuáles son las ventajas de usar IronXL para la conversión de Excel a XML?

IronXL ofrece una API sencilla que simplifica el proceso de conversión de archivos Excel a XML. Maneja la conversión internamente, lo que permite una fácil integración con aplicaciones .NET sin la necesidad de iteración manual de datos.

¿Es IronXL compatible con formatos XLS y XLSX para la conversión?

Sí, IronXL es compatible con formatos de archivo XLS y XLSX, proporcionando versatilidad para diversas tareas de manipulación y conversión de archivos Excel.

¿Cuáles son los pasos de instalación de IronXL en un proyecto de Visual Studio?

Para instalar IronXL en Visual Studio, puedes usar la Consola del Administrador de Paquetes de NuGet con el comando Install-Package IronXL, o puedes buscar IronXL en el Administrador de Paquetes de NuGet e instalarlo directamente desde allí.

¿Cómo puedo asegurarme de desechar correctamente los objetos de IronXL después de su uso?

Después de usar objetos de IronXL, asegúrate de desecharlos correctamente para liberar recursos. Esto se puede hacer llamando al método Dispose en los objetos una vez que ya no se necesiten.

¿Qué lenguajes de programación son compatibles con IronXL?

IronXL se puede usar con varios lenguajes .NET, incluidos C# y VB.NET, convirtiéndolo en una opción versátil para desarrolladores que trabajan en aplicaciones que requieren integración con Excel.

¿Qué opciones de licencia están disponibles para IronXL?

IronXL proporciona una edición comunitaria gratuita para uso no comercial con limitaciones, y para fines comerciales, versiones pagadas con características mejoradas y soporte están disponibles a través de suscripción o licencias perpetuas.

¿Cómo facilita IronXL la exportación de datos de Excel a otros formatos?

IronXL permite una extracción y exportación de datos sin problemas de archivos Excel a varios formatos, como XML y texto simple, mejorando la integración con bases de datos y otros sistemas.

Jordi Bardia
Ingeniero de Software
Jordi es más competente en Python, C# y C++. Cuando no está aprovechando sus habilidades en Iron Software, está programando juegos. Compartiendo responsabilidades para pruebas de productos, desarrollo de productos e investigación, Jordi agrega un valor inmenso a la mejora continua del producto. La experiencia variada lo mantiene ...
Leer más