Excel To XML Using LINQ

In this article we will show you the easiest way to convert Excel data into Xml files.

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.             }  
  14.             else if (txtXlFilePath.Text != "" && txtNodeName.Text != ""// Using Default Xml File Name  
  15.             {  
  16.                 if (File.Exists(txtXlFilePath.Text))  
  17.                 {  
  18.                     ConvertXml _Convert = new ConvertXml();  
  19.                     _Convert.CreateXltoXML(txtXlFilePath.Text, txtNodeName.Text);  
  20.                     MessageBox.Show("Conversion Completed!!");  
  21.                 }  
  22.             }  
  23.             else  
  24.             {  
  25.                 MessageBox.Show("Please Fill Required Feilds!!");  
  26.             }  
  27.         }  

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.   
  9. class ConvertXml  
  10.     {  

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.   
  27.         writer.WriteEndElement();  
  28.         writer.WriteEndDocument();  
  29.         writer.Close();  
  30.         if (File.Exists(XmlFile))  
  31.             IsCreated = true;  
  32.     }  
  33.     catch (Exception ex)  
  34.     {  
  35.     }  
  36.   
  37.     return IsCreated;  
  38.   
  39. }  
  40.   
  41. // Creating Xml File With Default FileName  
  42. public bool CreateXltoXML(string XlFile, string RowName)  
  43. {  
  44.     bool IsCreated = false;  
  45.     try  
  46.     {  
  47.         string XmlFile = XlFile.Replace(Path.GetExtension(XlFile), "") + ".xml"// Getting XMl file Name as Excel File Name  
  48.         DataTable dt = GetTableDataXl(XlFile);  
  49.         XmlTextWriter writer = new XmlTextWriter(XmlFile, System.Text.Encoding.UTF8);  
  50.         writer.WriteStartDocument(true);  
  51.         writer.Formatting = Formatting.Indented;  
  52.         writer.Indentation = 2;  
  53.         writer.WriteStartElement("tbl_" + RowName);  
  54.         List<string> ColumnNames = dt.Columns.Cast<DataColumn>().ToList().Select(x => x.ColumnName).ToList(); // Column Names List  
  55.         List<DataRow> RowList = dt.Rows.Cast<DataRow>().ToList();  
  56.         foreach (DataRow dr in RowList)  
  57.         {  
  58.             writer.WriteStartElement(RowName);  
  59.             for (int i = 0; i < ColumnNames.Count; i++) // Getting Node Names from DataTable Column Names  
  60.             {  
  61.                 writer.WriteStartElement(ColumnNames[i]);  
  62.                 writer.WriteString(dr.ItemArray[i].ToString());  
  63.                 writer.WriteEndElement();  
  64.             }  
  65.             writer.WriteEndElement();  
  66.         }  
  67.   
  68.         writer.WriteEndElement();  
  69.         writer.WriteEndDocument();  
  70.         writer.Close();  
  71.         if (File.Exists(XmlFile))  
  72.             IsCreated = true;  
  73.     }  
  74.     catch (Exception ex)  
  75.     {  
  76.     }  
  77.   
  78.     return IsCreated;  
  79.   
  80. }  

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.   
  20.             cmd.Connection = conn;  
  21.             //Fetch Fisrt Sheet Name  
  22.             conn.Open();  
  23.             DataTable dtSchema;  
  24.             dtSchema = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);  
  25.             string ExcelSheetName = dtSchema.Rows[0]["TABLE_NAME"].ToString();  
  26.             conn.Close();  
  27.             //Read all data from the Sheet to a Data Table  
  28.             conn.Open();  
  29.             cmd.CommandText = "SELECT * From [" + ExcelSheetName + "]";  
  30.             dataAdapter.SelectCommand = cmd;  
  31.             dataAdapter.Fill(dt); // Fill Sheet Data to Datatable  
  32.             conn.Close();  
  33.         }  
  34.         catch (Exception ex)  
  35.         { }  
  36.   
  37.         return dt;  
  38.     }  
  39. }  

I hope this will help you.