[C#] Hướng Dẫn Chuyển đổi Convert File Excel Sang định Dạng XML

Xin chào các bạn, bài viết hôm nay, mình sẽ hướng dẫn các bạn cách chuyển đổi file Excel sang định dạng XML trong lập trình C#.

- Cách chuyển đổi:

+ Đầu tiên đọc dữ liệu file Excel lên DataTable.

+ Foreach trên DataTable để chuyển Column trong table thành Node XML.

convert excel to xml C#

Thiết kế giao diện ứng dụng:

convert excel to xml

Hình ảnh bên dưới là kết quả chuyển đổi từ Excel sang XML

chuyển đổi excel sang xml lập trình csharp

1. Đầu tiên các bạn cần tạo một class ConvertXml.cs với source code C# bên dưới:

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.OleDb; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; using System.Xml.Linq; using System.IO; namespace ConvertXmlApp { class ConvertXml { // Creating Xml File With Custome FileName 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(); // Column Names List List<DataRow> RowList = dt.Rows.Cast<DataRow>().ToList(); foreach (DataRow dr in RowList) { writer.WriteStartElement(RowName); for (int i = 0; i < ColumnNames.Count; i++) // Getting Node Names from DataTable Column Names { 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; } // Creating Xml File With Default FileName public bool CreateXltoXML(string XlFile, string RowName) { bool IsCreated = false; try { string XmlFile = XlFile.Replace(Path.GetExtension(XlFile), "") + ".xml"; // Getting XMl file Name as Excel File Name 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(); // Column Names List List<DataRow> RowList = dt.Rows.Cast<DataRow>().ToList(); foreach (DataRow dr in RowList) { writer.WriteStartElement(RowName); for (int i = 0; i < ColumnNames.Count; i++) // Getting Node Names from DataTable Column Names { 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; } private DataTable GetTableDataXl(string XlFile) { DataTable dt = new DataTable(); try { string Ext = Path.GetExtension(XlFile); string connectionString = ""; if (Ext == ".xls") { //For Excel 97-03 connectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source =" + XlFile + "; Extended Properties = 'Excel 8.0;HDR=YES'"; } else if (Ext == ".xlsx") { //For Excel 07 and greater 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; //Fetch 1st Sheet Name conn.Open(); DataTable dtSchema; dtSchema = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); string ExcelSheetName = dtSchema.Rows[0]["TABLE_NAME"].ToString(); conn.Close(); //Read all data from the Sheet to a Data Table conn.Open(); cmd.CommandText = "SELECT * From [" + ExcelSheetName + "]"; dataAdapter.SelectCommand = cmd; dataAdapter.Fill(dt); // Fill Sheet Data to Datatable conn.Close(); } catch (Exception ex) { } return dt; } } }

2. Source code cho Form Main và click sự kiện Convert file XML

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; namespace ConvertXmlApp { public partial class ConvertXmlFrom : Form { public ConvertXmlFrom() { InitializeComponent(); } private void btnBrowseFolder_Click(object sender, EventArgs e) { DialogResult drResult = OFD.ShowDialog(); if (drResult == System.Windows.Forms.DialogResult.OK) txtXlFilePath.Text = OFD.FileName; } private void btnConvert_Click(object sender, EventArgs e) { if (chkCustomeName.Checked && txtCustomeFileName.Text != "" && txtXlFilePath.Text!="" && txtNodeName.Text!="") // using Custome Xml File Name { if (File.Exists(txtXlFilePath.Text)) { string CustXmlFilePath = Path.Combine(new FileInfo(txtXlFilePath.Text).DirectoryName, txtCustomeFileName.Text); // Ceating Path for Xml File ConvertXml _Convert = new ConvertXml(); _Convert.CreateXltoXML(CustXmlFilePath, txtXlFilePath.Text, txtNodeName.Text); // Xml File, EXcel File, Row Name MessageBox.Show("Conversion Completed!!"); } } else if (txtXlFilePath.Text != "" && txtNodeName.Text != "") // Using Default Xml File Name { 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!!"); } } } }

Chi tiết các bạn có thể download source để tham khảo nhé.

HAPPY CODING heart

DOWNLOAD SOURCE

Tags: excelxmldatatable

Từ khóa » Chuyển Từ File Excel Sang Xml