Click here to Skip to main content
15,896,339 members
Articles / Desktop Programming / Windows Forms
Tip/Trick

Convert XML File to Excel File

Rate me:
Please Sign up or sign in to vote.
4.44/5 (8 votes)
27 Nov 2017CPOL2 min read 41.8K   1.9K   12   7
Converting XML Data into DataTable and Exporting DataTable into Excel File

Introduction

In this tip, I am going to share with you the conversion methods of XML to Excel in C#.

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

Targeted Audiences

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’.

Create New Project

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

Add Reference

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

So, here, our UI looks like the following:

UI Design

Now, code the click event of the button to browse computer files so that the user can select his XML file. Set Filter in OpenFileDialog tool ‘XML File (*.xml)|*.xml|All files (*.*)|*.*’ so it’s preferred Excel files while browsing the file. User can give custom Excel file name by checking ‘Excel File Name’ checkbox and enter Excel's file in respective textbox. And after that, user can convert XML file by simply clicking on ‘Convert’ Button. So, double-click on the ‘Convert’ button to open the click event.

Code

C#
using System.Data;
using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Excel;

Code for the file browse button click event:

C#
private void btnBrowseFolder_Click(object sender, EventArgs e)
 {
     DialogResult drResult = OFD.ShowDialog();
     if (drResult == System.Windows.Forms.DialogResult.OK)
         txtXmlFilePath.Text = OFD.FileName;
 }

Code for the ‘Convert’ button click event:

C#
private void btnConvert_Click(object sender, EventArgs e)
        {
            // Resetting the progress bar Value
            progressBar1.Value = 0;

            if (chkCustomeName.Checked && txtCustomeFileName.Text != "" && 
            txtXmlFilePath.Text != "") // using Custom Xml File Name
            {
                if (File.Exists(txtXmlFilePath.Text)) // Checking XMl File is Exist or Not
                {
                    string CustXmlFilePath = 
                           Path.Combine(new FileInfo(txtXmlFilePath.Text).DirectoryName, 
                    txtCustomeFileName.Text); // Creating Path for Xml Files
                    System.Data.DataTable dt = CreateDataTableFromXml(txtXmlFilePath.Text);
                    ExportDataTableToExcel(dt, CustXmlFilePath);

                    MessageBox.Show("Conversion Completed!!");
                }

            }
            else if (!chkCustomeName.Checked || 
                         txtXmlFilePath.Text != "") // Using Default Xml File Name
            {
                if (File.Exists(txtXmlFilePath.Text)) // Checking XMl File is Exist or Not
                {
                    FileInfo fi = new FileInfo(txtXmlFilePath.Text);
                    string XlFile = fi.DirectoryName + "\\" + fi.Name.Replace
                    (fi.Extension,".xlsx"); // CReating Default File Name
                    System.Data.DataTable dt = CreateDataTableFromXml
                    (txtXmlFilePath.Text); // Getting XML Data into DataTable
                    ExportDataTableToExcel(dt, XlFile);

                    MessageBox.Show("Conversion Completed!!");
                }
            }
            else
            {
                MessageBox.Show("Please Fill Required Fields!!");
            }
        }

In "CreateDataTableFromXml" function, we are simply converting XML data into ‘DataTable’. This function returns a DataTable and we export this datatable into the Excel file.

C#
// Creating DataTable With Xml Data
       public System.Data.DataTable CreateDataTableFromXml(string XmlFile)
       {
           System.Data.DataTable Dt = new System.Data.DataTable();
           try
           {
               DataSet ds = new DataSet();
               ds.ReadXml(XmlFile);
               Dt.Load(ds.CreateDataReader());
           }
           catch (Exception ex)
           {

           }
           return Dt;
       }

In "ExportDataTableToExcel" function, we pass DataTable and Excel File Name through function’s parameters. We are creating new Excel file and we are exporting DataTable’s Column Names as Header row in Excel File. And also exporting DataRow as Excel rows.

C#
private void ExportDataTableToExcel(System.Data.DataTable table, string Xlfile)
        {
            Microsoft.Office.Interop.Excel.Application excel = 
                                 new Microsoft.Office.Interop.Excel.Application();
            Workbook book = excel.Application.Workbooks.Add(Type.Missing);
            excel.Visible = false;
            excel.DisplayAlerts = false;
            Worksheet excelWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)book.ActiveSheet;
            excelWorkSheet.Name = table.TableName;

            progressBar1.Maximum = table.Columns.Count;
            for (int i = 1; i < table.Columns.Count + 1; i++) // Creating Header Column In Excel
            {
                excelWorkSheet.Cells[1, i] = table.Columns[i - 1].ColumnName;
                if (progressBar1.Value < progressBar1.Maximum)
                {
                    progressBar1.Value++;
                    int percent = (int)(((double)progressBar1.Value / 
                    (double)progressBar1.Maximum) * 100);
                    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));
                    System.Windows.Forms.Application.DoEvents();
                }
            }

            progressBar1.Maximum = table.Rows.Count;
            for (int j = 0; j < table.Rows.Count; j++) // Exporting Rows in Excel
            {
                for (int k = 0; k < table.Columns.Count; k++)
                {
                    excelWorkSheet.Cells[j + 2, k + 1] = table.Rows[j].ItemArray[k].ToString();
                }

                if (progressBar1.Value < progressBar1.Maximum)
                {
                    progressBar1.Value++;
                    int percent = (int)(((double)progressBar1.Value / 
                                         (double)progressBar1.Maximum) * 100);
                    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));
                    System.Windows.Forms.Application.DoEvents();
                }
            }

            book.SaveAs(Xlfile);
            book.Close(true);
            excel.Quit();

            Marshal.ReleaseComObject(book);
            Marshal.ReleaseComObject(book);
            Marshal.ReleaseComObject(excel);
        }

Conclusion

By using these easy and simple methods, we can convert 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 and also we can display DataTable’s Data in “DataGridView”, simply setting DataGridView property “DataSource” to DataTable.

Hope this will help you and you would like this article.

Please give your valuable feedback in the comments below.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer Prothious Engineering Services
India India
Team Leader .Net Developer, Working on Microsoft Technology Asp.Net, C#, SQL, Windows Application, Web Application.

Achievements :

13th January 2018 - Article of the Day - ASP.NET Community (SignalR Chat App With ASP.NET WebForm And BootStrap - Part One)


14th February 2018 - Article of the Day - ASP.NET Community (SignalR Chat App With ASP.NET WebForm And BootStrap - Part Two)

3rd March 2018 - Article of the Day - ASP.NET Community (SignalR Chat App With ASP.NET WebForm And BootStrap - Part Three)

Comments and Discussions

 
QuestionJIT issue Pin
Sakti Mohapatra14-Mar-18 7:44
Sakti Mohapatra14-Mar-18 7:44 
When I click on Convert file, I am getting JIT error. Can you help please?

<pre>See the end of this message for details on invoking
just-in-time (JIT) debugging instead of this dialog box.

************** Exception Text **************
System.Runtime.InteropServices.COMException (0x800A03EC): Exception from HRESULT: 0x800A03EC
at Microsoft.Office.Interop.Excel._Worksheet.set_Name(String RHS)
at ConvertXmlToXl.Form1.ExportDataTableToExcel(DataTable table, String Xlfile) in C:\Users\sakti\Desktop\Development\ASPNet\ConvertXmlToXl\ConvertXmlToXl\ConvertXmlToXl\Form1.cs:line 96
at ConvertXmlToXl.Form1.btnConvert_Click(Object sender, EventArgs e) in C:\Users\sakti\Desktop\Development\ASPNet\ConvertXmlToXl\ConvertXmlToXl\ConvertXmlToXl\Form1.cs:line 44
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)


************** Loaded Assemblies **************
mscorlib
Assembly Version: 4.0.0.0
Win32 Version: 4.7.2633.0 built by: NET471REL1LAST_C
CodeBase: file:///C:/Windows/Microsoft.NET/Framework/v4.0.30319/mscorlib.dll
----------------------------------------
ConvertXmlToXl
Assembly Version: 1.0.0.0
Win32 Version: 1.0.0.0
CodeBase: file:///C:/Users/sakti/Desktop/Development/ASPNet/ConvertXmlToXl/ConvertXmlToXl/ConvertXmlToXl/bin/Debug/ConvertXmlToXl.exe
----------------------------------------
System.Windows.Forms
Assembly Version: 4.0.0.0
Win32 Version: 4.7.2556.0 built by: NET471REL1
CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_MSIL/System.Windows.Forms/v4.0_4.0.0.0__b77a5c561934e089/System.Windows.Forms.dll
----------------------------------------
System
Assembly Version: 4.0.0.0
Win32 Version: 4.7.2556.0 built by: NET471REL1
CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_MSIL/System/v4.0_4.0.0.0__b77a5c561934e089/System.dll
----------------------------------------
System.Drawing
Assembly Version: 4.0.0.0
Win32 Version: 4.7.2556.0 built by: NET471REL1
CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_MSIL/System.Drawing/v4.0_4.0.0.0__b03f5f7f11d50a3a/System.Drawing.dll
----------------------------------------
System.Configuration
Assembly Version: 4.0.0.0
Win32 Version: 4.7.2556.0 built by: NET471REL1
CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_MSIL/System.Configuration/v4.0_4.0.0.0__b03f5f7f11d50a3a/System.Configuration.dll
----------------------------------------
System.Core
Assembly Version: 4.0.0.0
Win32 Version: 4.7.2633.0 built by: NET471REL1LAST_C
CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_MSIL/System.Core/v4.0_4.0.0.0__b77a5c561934e089/System.Core.dll
----------------------------------------
System.Xml
Assembly Version: 4.0.0.0
Win32 Version: 4.7.2612.0 built by: NET471REL1LAST_B
CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_MSIL/System.Xml/v4.0_4.0.0.0__b77a5c561934e089/System.Xml.dll
----------------------------------------
Accessibility
Assembly Version: 4.0.0.0
Win32 Version: 4.7.2556.0 built by: NET471REL1
CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_MSIL/Accessibility/v4.0_4.0.0.0__b03f5f7f11d50a3a/Accessibility.dll
----------------------------------------
System.Data
Assembly Version: 4.0.0.0
Win32 Version: 4.7.2633.0 built by: NET471REL1LAST_C
CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_32/System.Data/v4.0_4.0.0.0__b77a5c561934e089/System.Data.dll
----------------------------------------
System.Numerics
Assembly Version: 4.0.0.0
Win32 Version: 4.7.2556.0 built by: NET471REL1
CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_MSIL/System.Numerics/v4.0_4.0.0.0__b77a5c561934e089/System.Numerics.dll
----------------------------------------
Microsoft.CSharp
Assembly Version: 4.0.0.0
Win32 Version: 4.7.2556.0
CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_MSIL/Microsoft.CSharp/v4.0_4.0.0.0__b03f5f7f11d50a3a/Microsoft.CSharp.dll
----------------------------------------
Microsoft.Office.Interop.Excel
Assembly Version: 15.0.0.0
Win32 Version: 15.0.4569.1506
CodeBase: file:///C:/WINDOWS/assembly/GAC_MSIL/Microsoft.Office.Interop.Excel/15.0.0.0__71e9bce111e9429c/Microsoft.Office.Interop.Excel.dll
----------------------------------------
office
Assembly Version: 15.0.0.0
Win32 Version: 15.0.5007.1000
CodeBase: file:///C:/WINDOWS/assembly/GAC_MSIL/office/15.0.0.0__71e9bce111e9429c/office.dll
----------------------------------------
System.Dynamic
Assembly Version: 4.0.0.0
Win32 Version: 4.7.2556.0
CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_MSIL/System.Dynamic/v4.0_4.0.0.0__b03f5f7f11d50a3a/System.Dynamic.dll
----------------------------------------
Anonymously Hosted DynamicMethods Assembly
Assembly Version: 0.0.0.0
Win32 Version: 4.7.2633.0 built by: NET471REL1LAST_C
CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_32/mscorlib/v4.0_4.0.0.0__b77a5c561934e089/mscorlib.dll
----------------------------------------

************** JIT Debugging **************
To enable just-in-time (JIT) debugging, the .config file for this
application or computer (machine.config) must have the
jitDebugging value set in the system.windows.forms section.
The application must also be compiled with debugging
enabled.

For example:

<configuration>
<system.windows.forms jitDebugging="true" />
</configuration>

When JIT debugging is enabled, any unhandled exception
will be sent to the JIT debugger registered on the computer
rather than be handled by this dialog box.
QuestionThe name 'OFD' does not exist in the current context Pin
Shamina Maharaj 29-Nov-17 1:45
professionalShamina Maharaj 29-Nov-17 1:45 
AnswerRe: The name 'OFD' does not exist in the current context Pin
Altaf Ansari29-Nov-17 2:28
Altaf Ansari29-Nov-17 2:28 
GeneralRe: The name 'OFD' does not exist in the current context Pin
Shamina Maharaj 29-Nov-17 21:34
professionalShamina Maharaj 29-Nov-17 21:34 
GeneralRe: The name 'OFD' does not exist in the current context Pin
Altaf Ansari29-Nov-17 22:01
Altaf Ansari29-Nov-17 22:01 
QuestionCode should be improved Pin
Member 1297152628-Nov-17 20:45
Member 1297152628-Nov-17 20:45 
AnswerRe: Code should be improved Pin
Altaf Ansari28-Nov-17 23:37
Altaf Ansari28-Nov-17 23:37 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.