In this article we will show you the easiest way to convert Excel data into Xml files. First getting Data from the Excel file and by using OLEDB in Data Table then Exporting this data table into XML, here you will learn the XML Conecepts like writing the xml document using XmlTextWriter.

Targeted Audiences

People with basic knowledge of C#.

Explanation

Things to do,

  • Make a C# WinForm application.
  • Create Excel File / can use Exists file.
  • Create UI
  • Code

There is a certain way to convert Excel file to Xml... For example using Excel Library (Com Component)

  1. using Microsoft.Office.Interop.Excel

But in my opinion there might be some problem as it used the Excel application in a background process and it creates complications in coding.

Step 1

Open a new Project

LINQ

Step 2

Rename the form Name ‘ConvertXmlFrom’

Step 3

Add Controls as below,

LINQ

Use Namespace on top

  1. using System.Windows.Forms;
  2. using System.IO;

On File Browse Click

  1. private void btnBrowseFolder_Click(object sender, EventArgs e)
  2. {
  3. DialogResult drResult = FBD.ShowDialog();
  4. if (drResult == System.Windows.Forms.DialogResult.OK)
  5. txtXlFilePath.Text = FBD.SelectedPath;
  6. }

On Convert Button Click

  1. private void btnConvert_Click(object sender, EventArgs e)
  2. {
  3. if (chkCustomeName.Checked && txtCustomeFileName.Text != "" && txtXlFilePath.Text!="" && txtNodeName.Text!="") // using Custome Xml File Name
  4. {
  5. if (File.Exists(txtXlFilePath.Text))
  6. {
  7. string CustXmlFilePath = Path.Combine(new FileInfo(txtXlFilePath.Text).DirectoryName, txtCustomeFileName.Text); // Ceating Path for Xml File
  8. ConvertXml _Convert = new ConvertXml();
  9. _Convert.CreateXltoXML(CustXmlFilePath, txtXlFilePath.Text, txtNodeName.Text); // Xml File, EXcel File, Row Name
  10. MessageBox.Show("Conversion Completed!!");
  11. }
  12. }
  13. else if (txtXlFilePath.Text != "" && txtNodeName.Text != "") // Using Default Xml File Name
  14. {
  15. if (File.Exists(txtXlFilePath.Text))
  16. {
  17. ConvertXml _Convert = new ConvertXml();
  18. _Convert.CreateXltoXML(txtXlFilePath.Text, txtNodeName.Text);
  19. MessageBox.Show("Conversion Completed!!");
  20. }
  21. }
  22. else
  23. {
  24. MessageBox.Show("Please Fill Required Feilds!!");
  25. }
  26. }

Step 4

Add New Class with Name ‘ConvertXml.cs’
  1. Use Namespace on top :
  2. using System.Xml;
  3. using System.Xml.Linq;
  4. using System.IO;
  5. using System.Data;
  6. using System.Data.OleDb;
  7. using System.Linq;
  8. class ConvertXml
  9. {

Here is an example of method Overloading. In the first method we are passing custom Xml file Name.

In the other method it will use default file name which it is getting from the Excel file.

  1. // Creating Xml File With Custome FileName
  2. public bool CreateXltoXML(string XmlFile, string XlFile, string RowName)
  3. {
  4. bool IsCreated = false;
  5. try
  6. {
  7. DataTable dt = GetTableDataXl(XlFile);
  8. XmlTextWriter writer = new XmlTextWriter(XmlFile, System.Text.Encoding.UTF8);
  9. writer.WriteStartDocument(true);
  10. writer.Formatting = Formatting.Indented;
  11. writer.Indentation = 2;
  12. writer.WriteStartElement("tbl_" + RowName);
  13. List<string> ColumnNames = dt.Columns.Cast<DataColumn>().ToList().Select(x => x.ColumnName).ToList(); // Column Names List
  14. List<DataRow> RowList = dt.Rows.Cast<DataRow>().ToList();
  15. foreach (DataRow dr in RowList)
  16. {
  17. writer.WriteStartElement(RowName);
  18. for (int i = 0; i < ColumnNames.Count; i++) // Getting Node Names from DataTable Column Names
  19. {
  20. writer.WriteStartElement(ColumnNames[i]);
  21. writer.WriteString(dr.ItemArray[i].ToString());
  22. writer.WriteEndElement();
  23. }
  24. writer.WriteEndElement();
  25. }
  26. writer.WriteEndElement();
  27. writer.WriteEndDocument();
  28. writer.Close();
  29. if (File.Exists(XmlFile))
  30. IsCreated = true;
  31. }
  32. catch (Exception ex)
  33. {
  34. }
  35. return IsCreated;
  36. }
  37. // Creating Xml File With Default FileName
  38. public bool CreateXltoXML(string XlFile, string RowName)
  39. {
  40. bool IsCreated = false;
  41. try
  42. {
  43. string XmlFile = XlFile.Replace(Path.GetExtension(XlFile), "") + ".xml"; // Getting XMl file Name as Excel File Name
  44. DataTable dt = GetTableDataXl(XlFile);
  45. XmlTextWriter writer = new XmlTextWriter(XmlFile, System.Text.Encoding.UTF8);
  46. writer.WriteStartDocument(true);
  47. writer.Formatting = Formatting.Indented;
  48. writer.Indentation = 2;
  49. writer.WriteStartElement("tbl_" + RowName);
  50. List<string> ColumnNames = dt.Columns.Cast<DataColumn>().ToList().Select(x => x.ColumnName).ToList(); // Column Names List
  51. List<DataRow> RowList = dt.Rows.Cast<DataRow>().ToList();
  52. foreach (DataRow dr in RowList)
  53. {
  54. writer.WriteStartElement(RowName);
  55. for (int i = 0; i < ColumnNames.Count; i++) // Getting Node Names from DataTable Column Names
  56. {
  57. writer.WriteStartElement(ColumnNames[i]);
  58. writer.WriteString(dr.ItemArray[i].ToString());
  59. writer.WriteEndElement();
  60. }
  61. writer.WriteEndElement();
  62. }
  63. writer.WriteEndElement();
  64. writer.WriteEndDocument();
  65. writer.Close();
  66. if (File.Exists(XmlFile))
  67. IsCreated = true;
  68. }
  69. catch (Exception ex)
  70. {
  71. }
  72. return IsCreated;
  73. }

Here we are creating Datatable from Excel Data; it’s by default using the First Sheet.

  1. private DataTable GetTableDataXl(string XlFile)
  2. {
  3. DataTable dt = new DataTable();
  4. try
  5. {
  6. string Ext = Path.GetExtension(XlFile);
  7. string connectionString = "";
  8. if (Ext == ".xls")
  9. { //For Excel 97-03
  10. connectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source =" + XlFile + "; Extended Properties = 'Excel 8.0;HDR=YES'";
  11. }
  12. else if (Ext == ".xlsx")
  13. { //For Excel 07 and greater
  14. connectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source =" + XlFile + "; Extended Properties = 'Excel 8.0;HDR=YES'";
  15. }
  16. OleDbConnection conn = new OleDbConnection(connectionString);
  17. OleDbCommand cmd = new OleDbCommand();
  18. OleDbDataAdapter dataAdapter = new OleDbDataAdapter();
  19. cmd.Connection = conn;
  20. //Fetch Fisrt Sheet Name
  21. conn.Open();
  22. DataTable dtSchema;
  23. dtSchema = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
  24. string ExcelSheetName = dtSchema.Rows[0]["TABLE_NAME"].ToString();
  25. conn.Close();
  26. //Read all data from the Sheet to a Data Table
  27. conn.Open();
  28. cmd.CommandText = "SELECT * From [" + ExcelSheetName + "]";
  29. dataAdapter.SelectCommand = cmd;
  30. dataAdapter.Fill(dt); // Fill Sheet Data to Datatable
  31. conn.Close();
  32. }
  33. catch (Exception ex)
  34. { }
  35. return dt;
  36. }
  37. }

I hope this will help you. Please give your valuable feedback in the comments section.