Convert XML File To Excel File

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,

  • Make a C# WinForm application.
  • Add a reference.
  • Create UI
  • Code

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;  
  • Code for the file "Browse" button click event.
    1. private void btnBrowseFolder_Click(object sender, EventArgs e)  
    2. {  
    3.     DialogResult drResult = OFD.ShowDialog();  
    4.      if (drResult == System.Windows.Forms.DialogResult.OK)  
    5.           txtXmlFilePath.Text = OFD.FileName;  
    6. }  
  • Code for the ‘Convert’ button click event.
    1. private void btnConvert_Click(object sender, EventArgs e)  
    2.         {  
    3.             progressBar1.Value = 0;  
    4.             if (chkCustomeName.Checked && txtCustomeFileName.Text != "" && txtXmlFilePath.Text != ""// using Custome Xml File Name  
    5.             {  
    6.                 if (File.Exists(txtXmlFilePath.Text))  
    7.                 {  
    8.                     string CustXmlFilePath = Path.Combine(new FileInfo(txtXmlFilePath.Text).DirectoryName, txtCustomeFileName.Text); // Ceating Path for Xml Files  
    9.                     System.Data.DataTable dt = CreateDataTableFromXml(txtXmlFilePath.Text);  
    10.                     ExportDataTableToExcel(dt, CustXmlFilePath);  
    11.   
    12.                     MessageBox.Show("Conversion Completed!!");  
    13.                 }  
    14.   
    15.             }  
    16.             else if (!chkCustomeName.Checked || txtXmlFilePath.Text != ""// Using Default Xml File Name  
    17.             {  
    18.                 if (File.Exists(txtXmlFilePath.Text))  
    19.                 {  
    20.                     FileInfo fi = new FileInfo(txtXmlFilePath.Text);  
    21.                     string XlFile = fi.DirectoryName + "\\" + fi.Name.Replace(fi.Extension,".xlsx");  
    22.                     System.Data.DataTable dt = CreateDataTableFromXml(txtXmlFilePath.Text);  
    23.                     ExportDataTableToExcel(dt, XlFile);  
    24.   
    25.                     MessageBox.Show("Conversion Completed!!");  
    26.                 }  
    27.             }  
    28.             else  
    29.             {  
    30.                 MessageBox.Show("Please Fill Required Feilds!!");  
    31.             }  
    32.         } 
  • In ‘CreateDataTableFromXml’ function, we are simply converting the XML data into ‘DataTable’. This function returns a DataTable and we export this datatable into the Excel file.
    1. // Creating DataTable With Xml Data  
    2.     public System.Data.DataTable CreateDataTableFromXml(string XmlFile)  
    3.         {  
    4.   
    5.             System.Data.DataTable Dt = new System.Data.DataTable();   
    6.             try  
    7.             {  
    8.                 DataSet ds = new DataSet();  
    9.                 ds.ReadXml(XmlFile);  
    10.                 Dt.Load(ds.CreateDataReader());  
    11.   
    12.             }  
    13.             catch (Exception ex)  
    14.             {  
    15.   
    16.             }  
    17.             return Dt;  
    18.         } 
  • In ‘ExportDataTableToExcel’ function, we are passing the DataTable and Excel file name through function’s parameters. We are creating a new Excel file and we are exporting DataTable’s column names as Header row in that Excel file. And also, exporting the DataRow as Excel rows.
    1. private void ExportDataTableToExcel(System.Data.DataTable table, string Xlfile)  
    2. {  
    3.   
    4.     Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();  
    5.     Workbook book = excel.Application.Workbooks.Add(Type.Missing);  
    6.     excel.Visible = false;  
    7.     excel.DisplayAlerts = false;  
    8.     Worksheet excelWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)book.ActiveSheet;  
    9.     excelWorkSheet.Name = table.TableName;  
    10.   
    11.     progressBar1.Maximum = table.Columns.Count;  
    12.     for (int i = 1; i < table.Columns.Count + 1; i++) // Creating Header Column In Excel  
    13.     {  
    14.         excelWorkSheet.Cells[1, i] = table.Columns[i - 1].ColumnName;  
    15.         if (progressBar1.Value < progressBar1.Maximum)  
    16.         {  
    17.             progressBar1.Value++;  
    18.             int percent = (int)(((double)progressBar1.Value / (double)progressBar1.Maximum) * 100);  
    19.             progressBar1.CreateGraphics().DrawString(percent.ToString() + "%"new System.Drawing.Font("Arial", (float)8.25, FontStyle.Regular), Brushes.Black, new PointF(progressBar1.Width / 2 - 10, progressBar1.Height / 2 - 7));  
    20.             System.Windows.Forms.Application.DoEvents();  
    21.         }  
    22.     }  
    23.   
    24.   
    25.     progressBar1.Maximum = table.Rows.Count;  
    26.     for (int j = 0; j < table.Rows.Count; j++) // Exporting Rows in Excel  
    27.     {  
    28.         for (int k = 0; k < table.Columns.Count; k++)  
    29.         {  
    30.             excelWorkSheet.Cells[j + 2, k + 1] = table.Rows[j].ItemArray[k].ToString();  
    31.         }  
    32.   
    33.         if (progressBar1.Value < progressBar1.Maximum)  
    34.         {  
    35.             progressBar1.Value++;  
    36.             int percent = (int)(((double)progressBar1.Value / (double)progressBar1.Maximum) * 100);  
    37.             progressBar1.CreateGraphics().DrawString(percent.ToString() + "%"new System.Drawing.Font("Arial", (float)8.25, FontStyle.Regular), Brushes.Black, new PointF(progressBar1.Width / 2 - 10, progressBar1.Height / 2 - 7));  
    38.             System.Windows.Forms.Application.DoEvents();  
    39.         }  
    40.     }  
    41.   
    42.   
    43.     book.SaveAs(Xlfile);  
    44.     book.Close(true);  
    45.     excel.Quit();  
    46.   
    47.     Marshal.ReleaseComObject(book);  
    48.     Marshal.ReleaseComObject(book);  
    49.     Marshal.ReleaseComObject(excel);  
    50.   
    51. }  

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.

Up Next
    Ebook Download
    View all
    Learn
    View all