In this article, I am going to share with you the method of converting an XML file to Excel in C#.

Here, we are going to learn to read XML files in C# Windows.Form applications. We are going to make a small single-form application which takes an XML file from the user and converts that XML Data to Excel Data and returns an Excel file.

Targeted Audience

The targeted audience is people with basic knowledge of C#.

Explanation

Things to do,

Create a new project and give it a suitable name as I gave the project name - ‘ConvertXmlToXl’.

Convert XML File To Excel File

After creating the project, you have to add a reference named “Microsoft Excel Object library” in your project. You will find this reference in ‘COM’ Section.

Convert XML File To Excel File

Now, make a UI which contains two Buttons, two Textboxes, one CheckBox, a single ProgressBar, and an OpenFileDialog tool. A button is used to browse the XML file and checkbox to give an option to the user for custom Excel file name. And the ProgressBar is used to show the progress of the conversion. And, another button is for converting the XML file to Excel.

So, here, our UI looks like the following.

Convert XML File To Excel File

Now, code the click event of the button to browse the computer files so that the user can select the desired XML file.

Set Filter in OpenFileDialog tool ‘XML File (*.xml)|*.xml|All files (*.*)|*.*’ so it prefers Excel files while browsing the file.
The user can give custom Excel file name by checking ‘Excel File Name’ checkbox and enter the Excel file in the respective textbox.
After that, the user can conveXMLxml file by simply clicking on ‘Convert’ button. So, double-click on the ‘Convert’ button to open the click event.

Code

  1. using System.Data;
  2. using System.Runtime.InteropServices;
  3. using Microsoft.Office.Interop.Excel;

Conclusion

By using this easy and simple method, we can convert the XML files into DataTable. And from DataTable, we can export the data into Excel file or we can create a new Excel file and export the DataTable’s data. Also, we can display the DataTable’s data in “DataGridView”, Simply, sett the DataGridView property “DataSource” to DataTable.

Hope this will help you. Please give your valuable feedback in the comment section.