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#.
ExplanationThings 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)
- 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
Step 2
Rename the form Name ‘ConvertXmlFrom’
Step 3
Add Controls as below,
Use Namespace on top
- using System.Windows.Forms;
- using System.IO;
On File Browse Click
- private void btnBrowseFolder_Click(object sender, EventArgs e)
- {
- DialogResult drResult = FBD.ShowDialog();
- if (drResult == System.Windows.Forms.DialogResult.OK)
- txtXlFilePath.Text = FBD.SelectedPath;
- }
On Convert Button Click
- private void btnConvert_Click(object sender, EventArgs e)
- {
- if (chkCustomeName.Checked && txtCustomeFileName.Text != "" && txtXlFilePath.Text!="" && txtNodeName.Text!="")
- {
- if (File.Exists(txtXlFilePath.Text))
- {
- string CustXmlFilePath = Path.Combine(new FileInfo(txtXlFilePath.Text).DirectoryName, txtCustomeFileName.Text);
- ConvertXml _Convert = new ConvertXml();
- _Convert.CreateXltoXML(CustXmlFilePath, txtXlFilePath.Text, txtNodeName.Text);
- MessageBox.Show("Conversion Completed!!");
- }
-
- }
- else if (txtXlFilePath.Text != "" && txtNodeName.Text != "")
- {
- if (File.Exists(txtXlFilePath.Text))
- {
- ConvertXml _Convert = new ConvertXml();
- _Convert.CreateXltoXML(txtXlFilePath.Text, txtNodeName.Text);
- MessageBox.Show("Conversion Completed!!");
- }
- }
- else
- {
- MessageBox.Show("Please Fill Required Feilds!!");
- }
- }
Step 4
Add New Class with Name ‘ConvertXml.cs’
- Use Namespace on top :
- using System.Xml;
- using System.Xml.Linq;
- using System.IO;
- using System.Data;
- using System.Data.OleDb;
- using System.Linq;
-
- class ConvertXml
- {
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.
-
- public bool CreateXltoXML(string XmlFile, string XlFile, string RowName)
- {
- bool IsCreated = false;
- try
- {
- DataTable dt = GetTableDataXl(XlFile);
- XmlTextWriter writer = new XmlTextWriter(XmlFile, System.Text.Encoding.UTF8);
- writer.WriteStartDocument(true);
- writer.Formatting = Formatting.Indented;
- writer.Indentation = 2;
- writer.WriteStartElement("tbl_" + RowName);
- List<string> ColumnNames = dt.Columns.Cast<DataColumn>().ToList().Select(x => x.ColumnName).ToList();
- List<DataRow> RowList = dt.Rows.Cast<DataRow>().ToList();
- foreach (DataRow dr in RowList)
- {
- writer.WriteStartElement(RowName);
- for (int i = 0; i < ColumnNames.Count; i++)
- {
- writer.WriteStartElement(ColumnNames[i]);
- writer.WriteString(dr.ItemArray[i].ToString());
- writer.WriteEndElement();
- }
- writer.WriteEndElement();
- }
-
- writer.WriteEndElement();
- writer.WriteEndDocument();
- writer.Close();
- if (File.Exists(XmlFile))
- IsCreated = true;
- }
- catch (Exception ex)
- {
- }
-
- return IsCreated;
-
- }
-
-
- public bool CreateXltoXML(string XlFile, string RowName)
- {
- bool IsCreated = false;
- try
- {
- string XmlFile = XlFile.Replace(Path.GetExtension(XlFile), "") + ".xml";
- DataTable dt = GetTableDataXl(XlFile);
- XmlTextWriter writer = new XmlTextWriter(XmlFile, System.Text.Encoding.UTF8);
- writer.WriteStartDocument(true);
- writer.Formatting = Formatting.Indented;
- writer.Indentation = 2;
- writer.WriteStartElement("tbl_" + RowName);
- List<string> ColumnNames = dt.Columns.Cast<DataColumn>().ToList().Select(x => x.ColumnName).ToList();
- List<DataRow> RowList = dt.Rows.Cast<DataRow>().ToList();
- foreach (DataRow dr in RowList)
- {
- writer.WriteStartElement(RowName);
- for (int i = 0; i < ColumnNames.Count; i++)
- {
- writer.WriteStartElement(ColumnNames[i]);
- writer.WriteString(dr.ItemArray[i].ToString());
- writer.WriteEndElement();
- }
- writer.WriteEndElement();
- }
-
- writer.WriteEndElement();
- writer.WriteEndDocument();
- writer.Close();
- if (File.Exists(XmlFile))
- IsCreated = true;
- }
- catch (Exception ex)
- {
- }
-
- return IsCreated;
-
- }
Here we are creating Datatable from Excel Data; it’s by default using the First Sheet.
- private DataTable GetTableDataXl(string XlFile)
- {
- DataTable dt = new DataTable();
- try
- {
- string Ext = Path.GetExtension(XlFile);
- string connectionString = "";
- if (Ext == ".xls")
- {
- connectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source =" + XlFile + "; Extended Properties = 'Excel 8.0;HDR=YES'";
- }
- else if (Ext == ".xlsx")
- {
- connectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source =" + XlFile + "; Extended Properties = 'Excel 8.0;HDR=YES'";
- }
- OleDbConnection conn = new OleDbConnection(connectionString);
- OleDbCommand cmd = new OleDbCommand();
- OleDbDataAdapter dataAdapter = new OleDbDataAdapter();
-
- cmd.Connection = conn;
-
- conn.Open();
- DataTable dtSchema;
- dtSchema = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
- string ExcelSheetName = dtSchema.Rows[0]["TABLE_NAME"].ToString();
- conn.Close();
-
- conn.Open();
- cmd.CommandText = "SELECT * From [" + ExcelSheetName + "]";
- dataAdapter.SelectCommand = cmd;
- dataAdapter.Fill(dt);
- conn.Close();
- }
- catch (Exception ex)
- { }
-
- return dt;
- }
- }
I hope this will help you. Please give your valuable feedback in the comments section.