USING IRONXL

How to Convert An Excel File to XML in 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 $749. 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.

Frequently Asked Questions

What is Microsoft Excel used for?

Microsoft Excel is a multifunctional spreadsheet application used for organizing, analyzing, and visualizing data. It allows users to enter various types of input into individual cells and perform logical, statistical, and mathematical tasks.

How can I convert an Excel file to XML in C# using IronXL?

To convert an Excel file to XML using IronXL in C#, you need to create a Console project, install the IronXL library, initialize the IronXL object, load or create an Excel file, and use the SaveAsXml method within the XMLSaveOptions class to perform the conversion.

What are the key features of IronXL?

IronXL allows for easy data handling, Excel file creation and modification, supports both legacy and modern Excel formats, offers data extraction and export, and provides automation and efficiency through its comprehensive API.

How do I install IronXL in a Visual Studio project?

You can install IronXL in a Visual Studio project by using the NuGet Package Manager Console with the command 'Install-Package IronXL' or by searching for IronXL in the NuGet Package Manager and selecting the appropriate package.

What are the benefits of using IronXL for converting Excel files?

IronXL simplifies the process of converting Excel files to XML by offering a straightforward API, eliminating the need for manual iteration through Excel data, and ensuring easy integration with .NET applications.

Can IronXL be used for both XLS and XLSX file formats?

Yes, IronXL is compatible with both the older XLS format and the modern XLSX format, making it versatile for various Excel file manipulation tasks.

What is the SaveAsXml function in IronXL?

The SaveAsXml function in IronXL is used to convert Excel file data into XML format. It simplifies the process by internally handling the conversion and saving the output to a specified XML file.

Is IronXL suitable for commercial use?

IronXL offers a free Community Edition with limitations for non-commercial use. For commercial purposes, IronXL provides paid versions with enhanced features and support, available through subscription or perpetual licenses.

What programming languages can be used with IronXL?

IronXL can be used with C#, VB.NET, and other .NET languages, facilitating the development of applications that require Excel integration.

How does IronXL facilitate data extraction and export?

IronXL allows for seamless data extraction and export from Excel files to various formats such as XML and plain text, enhancing integration with databases and other systems.

Regan Pun
Software Engineer
Regan graduated from the University of Reading, with a BA in Electronic Engineering. Before joining Iron Software, his previous job roles had him laser-focused on single tasks; and what he most enjoys at Iron Software is the spectrum of work he gets to undertake, whether it’s adding value to sales, technical support, product development or marketing. He enjoys understanding the way developers are using the Iron Software library, and using that knowledge to continually improve documentation and develop the products.
< PREVIOUS
How to Read Data From CSV File And Store It In Database C#
NEXT >
How to Import an Excel File to SQL Database in VB .NET