Click here to Skip to main content
15,886,199 members
Articles / Programming Languages / XML

Convert Excel to XML file/XML Schema, and validate Excel against XML Schema

Rate me:
Please Sign up or sign in to vote.
4.63/5 (39 votes)
2 Jun 20054 min read 551.9K   33K   143  
Provides a utility and code library to convert an Excel file to XML file as well as generate XML Schema. It validates an Excel file against XML Schema.
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Xml.Schema ;
   
namespace ShowExcelAndXML
{
	/// <summary>
	/// Summary description for Form1.
	/// </summary>
	public class Form1 : System.Windows.Forms.Form
	{
		#region Declaration
		
		private string strFileName;
		private string strSheetNameRange;
		private DataSet dsFile;

		private ExcelXML.ExcelToXML obj;

		private System.Windows.Forms.OpenFileDialog dlgOpenFile;
		private System.Windows.Forms.DataGrid dataGrid1;
		private System.Windows.Forms.GroupBox groupBox1;
		private System.Windows.Forms.Button cmdOpenFile;
		private System.Windows.Forms.ComboBox cboSheetName;
		private System.Windows.Forms.TextBox txtFileName;
		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.Button button3;
		private System.Windows.Forms.SaveFileDialog dlgSave;
		private System.Windows.Forms.Button button1;
		private System.Windows.Forms.Button button2;
		private System.Windows.Forms.GroupBox groupBox2;
		private System.Windows.Forms.Button btnValidate;
		private System.Windows.Forms.RadioButton rdoWorkSheet;
		private System.Windows.Forms.RadioButton rdoWorkbook;
		private System.Windows.Forms.Button button4;
		private System.Windows.Forms.TextBox txtSchema;
		private System.Windows.Forms.TextBox txtRange;
		private System.Windows.Forms.Button button5;
		private System.Windows.Forms.TextBox txtData;
		private System.Windows.Forms.TextBox txtSchemaData;
		private System.Windows.Forms.Button btnBatchProcess;
		#endregion

		
		#region Windows Form Designer generated code

		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.Container components = null;

		public Form1()
		{
			//
			// Required for Windows Form Designer support
			//
			this.Text="Excel to XML" ;
			InitializeComponent();

			//
			// TODO: Add any constructor code after InitializeComponent call
			//
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}


		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.dlgOpenFile = new System.Windows.Forms.OpenFileDialog();
			this.dataGrid1 = new System.Windows.Forms.DataGrid();
			this.txtData = new System.Windows.Forms.TextBox();
			this.groupBox1 = new System.Windows.Forms.GroupBox();
			this.button5 = new System.Windows.Forms.Button();
			this.txtRange = new System.Windows.Forms.TextBox();
			this.cmdOpenFile = new System.Windows.Forms.Button();
			this.cboSheetName = new System.Windows.Forms.ComboBox();
			this.txtFileName = new System.Windows.Forms.TextBox();
			this.label1 = new System.Windows.Forms.Label();
			this.button3 = new System.Windows.Forms.Button();
			this.txtSchemaData = new System.Windows.Forms.TextBox();
			this.dlgSave = new System.Windows.Forms.SaveFileDialog();
			this.button1 = new System.Windows.Forms.Button();
			this.button2 = new System.Windows.Forms.Button();
			this.groupBox2 = new System.Windows.Forms.GroupBox();
			this.button4 = new System.Windows.Forms.Button();
			this.txtSchema = new System.Windows.Forms.TextBox();
			this.btnValidate = new System.Windows.Forms.Button();
			this.rdoWorkbook = new System.Windows.Forms.RadioButton();
			this.rdoWorkSheet = new System.Windows.Forms.RadioButton();
			this.btnBatchProcess = new System.Windows.Forms.Button();
			((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit();
			this.groupBox1.SuspendLayout();
			this.groupBox2.SuspendLayout();
			this.SuspendLayout();
			// 
			// dataGrid1
			// 
			this.dataGrid1.DataMember = "";
			this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText;
			this.dataGrid1.Location = new System.Drawing.Point(8, 144);
			this.dataGrid1.Name = "dataGrid1";
			this.dataGrid1.Size = new System.Drawing.Size(328, 164);
			this.dataGrid1.TabIndex = 0;
			// 
			// txtData
			// 
			this.txtData.Location = new System.Drawing.Point(344, 144);
			this.txtData.Multiline = true;
			this.txtData.Name = "txtData";
			this.txtData.ScrollBars = System.Windows.Forms.ScrollBars.Both;
			this.txtData.Size = new System.Drawing.Size(384, 312);
			this.txtData.TabIndex = 2;
			this.txtData.Text = "Data";
			// 
			// groupBox1
			// 
			this.groupBox1.Controls.AddRange(new System.Windows.Forms.Control[] {
																					this.button5,
																					this.txtRange,
																					this.cmdOpenFile,
																					this.cboSheetName,
																					this.txtFileName,
																					this.label1});
			this.groupBox1.Location = new System.Drawing.Point(8, 8);
			this.groupBox1.Name = "groupBox1";
			this.groupBox1.Size = new System.Drawing.Size(720, 64);
			this.groupBox1.TabIndex = 7;
			this.groupBox1.TabStop = false;
			this.groupBox1.Text = "Open Excel";
			// 
			// button5
			// 
			this.button5.Location = new System.Drawing.Point(568, 19);
			this.button5.Name = "button5";
			this.button5.TabIndex = 9;
			this.button5.Text = "Get Data";
			this.button5.Click += new System.EventHandler(this.button5_Click);
			// 
			// txtRange
			// 
			this.txtRange.Location = new System.Drawing.Point(456, 19);
			this.txtRange.Name = "txtRange";
			this.txtRange.TabIndex = 8;
			this.txtRange.Text = "";
			// 
			// cmdOpenFile
			// 
			this.cmdOpenFile.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
			this.cmdOpenFile.Location = new System.Drawing.Point(295, 19);
			this.cmdOpenFile.Name = "cmdOpenFile";
			this.cmdOpenFile.Size = new System.Drawing.Size(24, 21);
			this.cmdOpenFile.TabIndex = 7;
			this.cmdOpenFile.Text = "..";
			this.cmdOpenFile.Click += new System.EventHandler(this.cmdOpenFile_Click);
			// 
			// cboSheetName
			// 
			this.cboSheetName.Location = new System.Drawing.Point(327, 19);
			this.cboSheetName.Name = "cboSheetName";
			this.cboSheetName.Size = new System.Drawing.Size(121, 21);
			this.cboSheetName.TabIndex = 6;
			this.cboSheetName.Text = "Select Sheet";
			this.cboSheetName.SelectedIndexChanged += new System.EventHandler(this.cboSheetName_SelectedIndexChanged);
			// 
			// txtFileName
			// 
			this.txtFileName.Location = new System.Drawing.Point(75, 19);
			this.txtFileName.Name = "txtFileName";
			this.txtFileName.ReadOnly = true;
			this.txtFileName.Size = new System.Drawing.Size(216, 20);
			this.txtFileName.TabIndex = 5;
			this.txtFileName.Text = "Excel File Path";
			// 
			// label1
			// 
			this.label1.Location = new System.Drawing.Point(12, 19);
			this.label1.Name = "label1";
			this.label1.Size = new System.Drawing.Size(60, 21);
			this.label1.TabIndex = 0;
			this.label1.Text = "Excel File";
			this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
			// 
			// button3
			// 
			this.button3.Location = new System.Drawing.Point(576, 472);
			this.button3.Name = "button3";
			this.button3.Size = new System.Drawing.Size(144, 23);
			this.button3.TabIndex = 10;
			this.button3.Text = "Save Current Sheet XML";
			this.button3.Click += new System.EventHandler(this.button3_Click);
			// 
			// txtSchemaData
			// 
			this.txtSchemaData.Location = new System.Drawing.Point(8, 320);
			this.txtSchemaData.Multiline = true;
			this.txtSchemaData.Name = "txtSchemaData";
			this.txtSchemaData.ScrollBars = System.Windows.Forms.ScrollBars.Both;
			this.txtSchemaData.Size = new System.Drawing.Size(328, 144);
			this.txtSchemaData.TabIndex = 11;
			this.txtSchemaData.Text = "Schema";
			// 
			// dlgSave
			// 
			this.dlgSave.FileName = "doc1";
			// 
			// button1
			// 
			this.button1.Location = new System.Drawing.Point(403, 472);
			this.button1.Name = "button1";
			this.button1.Size = new System.Drawing.Size(168, 23);
			this.button1.TabIndex = 12;
			this.button1.Text = "Save XML File per Worksheet";
			this.button1.Click += new System.EventHandler(this.button1_Click);
			// 
			// button2
			// 
			this.button2.Location = new System.Drawing.Point(232, 472);
			this.button2.Name = "button2";
			this.button2.Size = new System.Drawing.Size(160, 23);
			this.button2.TabIndex = 13;
			this.button2.Text = "Save Workbook as XML File";
			this.button2.Click += new System.EventHandler(this.button2_Click);
			// 
			// groupBox2
			// 
			this.groupBox2.Controls.AddRange(new System.Windows.Forms.Control[] {
																					this.button4,
																					this.txtSchema,
																					this.btnValidate,
																					this.rdoWorkbook,
																					this.rdoWorkSheet});
			this.groupBox2.Location = new System.Drawing.Point(8, 77);
			this.groupBox2.Name = "groupBox2";
			this.groupBox2.Size = new System.Drawing.Size(720, 56);
			this.groupBox2.TabIndex = 14;
			this.groupBox2.TabStop = false;
			this.groupBox2.Text = "Scehma Validation";
			// 
			// button4
			// 
			this.button4.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
			this.button4.Location = new System.Drawing.Point(520, 24);
			this.button4.Name = "button4";
			this.button4.Size = new System.Drawing.Size(24, 21);
			this.button4.TabIndex = 12;
			this.button4.Text = "..";
			this.button4.Click += new System.EventHandler(this.button4_Click);
			// 
			// txtSchema
			// 
			this.txtSchema.Location = new System.Drawing.Point(296, 24);
			this.txtSchema.Name = "txtSchema";
			this.txtSchema.ReadOnly = true;
			this.txtSchema.Size = new System.Drawing.Size(216, 20);
			this.txtSchema.TabIndex = 11;
			this.txtSchema.Text = "txtSchemaData";
			// 
			// btnValidate
			// 
			this.btnValidate.Location = new System.Drawing.Point(616, 24);
			this.btnValidate.Name = "btnValidate";
			this.btnValidate.Size = new System.Drawing.Size(96, 23);
			this.btnValidate.TabIndex = 10;
			this.btnValidate.Text = "Validate";
			this.btnValidate.Click += new System.EventHandler(this.btnValidate_Click);
			// 
			// rdoWorkbook
			// 
			this.rdoWorkbook.Checked = true;
			this.rdoWorkbook.Location = new System.Drawing.Point(179, 21);
			this.rdoWorkbook.Name = "rdoWorkbook";
			this.rdoWorkbook.Size = new System.Drawing.Size(104, 23);
			this.rdoWorkbook.TabIndex = 1;
			this.rdoWorkbook.TabStop = true;
			this.rdoWorkbook.Text = "Workbook";
			// 
			// rdoWorkSheet
			// 
			this.rdoWorkSheet.Location = new System.Drawing.Point(27, 21);
			this.rdoWorkSheet.Name = "rdoWorkSheet";
			this.rdoWorkSheet.Size = new System.Drawing.Size(136, 23);
			this.rdoWorkSheet.TabIndex = 0;
			this.rdoWorkSheet.Text = "Current Work Sheet";
			// 
			// btnBatchProcess
			// 
			this.btnBatchProcess.Location = new System.Drawing.Point(48, 472);
			this.btnBatchProcess.Name = "btnBatchProcess";
			this.btnBatchProcess.Size = new System.Drawing.Size(160, 23);
			this.btnBatchProcess.TabIndex = 15;
			this.btnBatchProcess.Text = "Batch Process";
			this.btnBatchProcess.Click += new System.EventHandler(this.button6_Click);
			// 
			// Form1
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.ClientSize = new System.Drawing.Size(752, 502);
			this.Controls.AddRange(new System.Windows.Forms.Control[] {
																		  this.btnBatchProcess,
																		  this.groupBox2,
																		  this.button2,
																		  this.button1,
																		  this.txtSchemaData,
																		  this.groupBox1,
																		  this.txtData,
																		  this.dataGrid1,
																		  this.button3});
			this.Name = "Form1";
			this.Text = "Excel To XML v1.0";
			((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).EndInit();
			this.groupBox1.ResumeLayout(false);
			this.groupBox2.ResumeLayout(false);
			this.ResumeLayout(false);
			Application.ThreadException +=new System.Threading.ThreadExceptionEventHandler (this.HandleEx);    

		}

		private void HandleEx(object sender, System.Threading.ThreadExceptionEventArgs e)
		{
			MessageBox.Show("Oops !!! There is something teribaly wrong with the system. Restart again!!!!!!\n"+e.Exception.Message );  
		}
		#endregion

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main() 
		{
			Application.Run(new Form1());
		}
		#region Functionality
		private void cmdOpenFile_Click(object sender, System.EventArgs e)
		{
			try
			{
				dlgOpenFile.Filter="Excel File(*.xls)|*.xls"; 
				dlgOpenFile.ShowDialog();
				strFileName = dlgOpenFile.FileName;
				obj=new ExcelXML.ExcelToXML(strFileName,false);
				txtFileName.Text = strFileName; 
				string[] sheetnames = obj.GetExcelSheetNames();
				cboSheetName.Items.Clear();  
				cboSheetName.Items.AddRange(sheetnames);	
				cboSheetName.SelectedIndex = 0;  
			}
			catch(Exception ex)
			{
				MessageBox.Show(ex.Message);   
			}
		}

		private void cboSheetName_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			
		}

		private void btnExportXML_Click(object sender, System.EventArgs e)
		{
			if(txtFileName.Text.Trim()=="")
			{
				MessageBox.Show("Please First Open File..Then Export..!!!!!");
			}
			else
			{
				txtData.Text=obj.GetAllXML()[0];   
			}
		}

		private void button3_Click(object sender, System.EventArgs e)
		{
			dlgSave.Filter="XML File(*.xml)|*.xml";
			if(dlgSave.ShowDialog()==DialogResult.OK) 
			{
				obj.SaveSheetXML(dlgSave.FileName.ToString(),strSheetNameRange ,true); 
				MessageBox.Show(dlgSave.FileName.ToString() + " Saved");   
			}
		}

		private void button1_Click(object sender, System.EventArgs e)
		{
			dlgSave.Filter="XML File(*.xml)|*.xml";
			if(dlgSave.ShowDialog()==DialogResult.OK) 
			{
					
				obj.SaveXslXml(dlgSave.FileName.ToString(),true,true); 
				MessageBox.Show("Successfully Saved");   
			}
		}

		private void button2_Click(object sender, System.EventArgs e)
		{
			dlgSave.Filter="XML File(*.xml)|*.xml";
			if(dlgSave.ShowDialog()==DialogResult.OK) 
			{
				obj.SaveXslXml(dlgSave.FileName.ToString(),true,false); 
				MessageBox.Show("Successfully Saved"); 
			}
		}

		private void btnValidate_Click(object sender, System.EventArgs e)
		{
			try
			{
				string validationErro;
				if(rdoWorkbook.Checked==true)
                    validationErro=obj.ValidateXML(txtSchema.Text); 
				else
					validationErro=obj.ValidateXML(txtSchema.Text,strSheetNameRange); 
				if(validationErro =="")
					txtData.Text="Document is Valid";
				else
					txtData.Text = "Document is not Valid \r\n" +validationErro;   
			}
			catch(Exception ex)
			{
				MessageBox.Show(ex.Message);   
			}
		}

		private void button4_Click(object sender, System.EventArgs e)
		{
			dlgOpenFile.Filter="Scehma File(*.xsd)|*.xsd"; 
			if(dlgOpenFile.ShowDialog()== DialogResult.OK) 
						txtSchema.Text = dlgOpenFile.FileName;			
		}

		private void button5_Click(object sender, System.EventArgs e)
		{
			try
			{
				dsFile=new DataSet(); 
				DataTable dt=new DataTable(); 
				if(txtRange.Text=="")
					strSheetNameRange =  cboSheetName.Text.ToString();
				
				else
					strSheetNameRange =  cboSheetName.Text.ToString()+"|"+txtRange.Text;
					
				dt=obj.GetDataTable(strSheetNameRange); 
				dataGrid1.DataSource = dt.DefaultView ;
				txtData.Text = obj.GetXML(strSheetNameRange,false);   
				txtSchemaData.Text = obj.GetXMLSchema(strSheetNameRange);      
			}
			catch(Exception ex)
			{
				MessageBox.Show(ex.Message);   
			}
		}

		private void button6_Click(object sender, System.EventArgs e)
		{
			dlgOpenFile.Filter="Excel File(*.xls)|*.xls"; 
			dlgOpenFile.Multiselect=true; 
			dlgOpenFile.ShowDialog();
			string[] Files = dlgOpenFile.FileNames;
		
			if(Files.Length<2)
			{
				MessageBox.Show("Stupid !! cann't you do this using normal features.. this is for batch Process only");  
			}
			else
			{
				ExcelXML.ExcelToXML.BatchXMLConvert(Files,false); 
			}
		}
	
		#endregion
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Architect
United States United States
Currently he is working as Senior Soft. Engineer at Cognizant Technology Solution.He is involved in various project activities like System Architecture, Design, and Development. He is fond of conduction training for various technologies. He has have worked on various language and platforms. He is Microsoft and Oracle Certified professional. He is spending quantity and quality time in .Net world. He had also spoiled his hand with java, too.
If work is not demanding, he spends good time with his wife, Purvi.He
blogs
at WebDevs.com.

Comments and Discussions