- [DEVEXPRESS] Hỗ trợ tìm kiếm highlight không dấu và không khoảng cách trên Gridview Filter
- [C#] Chia sẻ source code phần mềm Image Downloader tải hàng loạt hình ảnh từ danh sách link url
- [C#] Chụp hình và quay video từ camera trên winform
- [C#] Chia sẽ full source code tách file Pdf thành nhiều file với các tùy chọn
- Giới thiệu về Stock Tracker Widget - Công cụ theo dõi cổ phiếu và cảnh báo giá tăng giảm bằng C# và WPF
- [VB.NET] Chia sẻ công cụ nhập số tiền tự động định dạng tiền tệ Việt Nam
- [VB.NET] Hướng dẫn fill dữ liệu từ winform vào Microsoft word
- [VB.NET] Hướng dẫn chọn nhiều dòng trên Datagridview
- Hướng Dẫn Đăng Nhập Nhiều Tài Khoản Zalo Trên Máy Tính Cực Kỳ Đơn Giản
- [C#] Chia sẻ source code phần mềm đếm số trang tập tin file PDF
- [C#] Cách Sử Dụng DeviceId trong C# Để Tạo Khóa Cho Ứng Dụng
- [SQLSERVER] Loại bỏ Restricted User trên database MSSQL
- [C#] Hướng dẫn tạo mã QRcode Style trên winform
- [C#] Hướng dẫn sử dụng temp mail service api trên winform
- [C#] Hướng dẫn tạo mã thanh toán VietQR Pay không sử dụng API trên winform
- [C#] Hướng Dẫn Tạo Windows Service Đơn Giản Bằng Topshelf
- [C#] Chia sẻ source code đọc dữ liệu từ Google Sheet trên winform
- [C#] Chia sẻ source code tạo mã QR MOMO đa năng Winform
- [C#] Chia sẻ source code phần mềm lên lịch tự động chạy ứng dụng Scheduler Task Winform
- [C#] Hướng dẫn download file từ Minio Server Winform
[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.

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

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

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 ColumnNames = dt.Columns.Cast().ToList().Select(x => x.ColumnName).ToList(); // Column Names List
                List RowList = dt.Rows.Cast().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 ColumnNames = dt.Columns.Cast().ToList().Select(x => x.ColumnName).ToList(); // Column Names List
                List RowList = dt.Rows.Cast().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 

![[C#] Hướng dẫn chuyển đổi convert file Excel sang định dạng XML](https://laptrinhvb.net/uploads/users/9a8cb514e4428e85fb4ca07588e9103f.png)

![[C#] Hướng dẫn tạo Auto Number trên Datagridview winform](https://laptrinhvb.net/uploads/source/new_image_baiviet/auto_number_datagridview_csharp.png)
![[C#] Hiệu ứng Water Effect Image cho Banner](https://laptrinhvb.net/uploads/source/csharp/water_effect_thumb.gif)
![[C#] Hướng dẫn lưu trữ mật khẩu ở Credential Manage Windows](https://laptrinhvb.net/uploads/source/new_image_baiviet/credentials_manager_windows.png)
![[C#] Hướng dẫn sử dụng iProgress để sử dụng progress bar trong lập trình csharp](https://laptrinhvb.net/uploads/source/csharp/progress_bar_csharp_thumb.jpg)
![[C#] Bắt sự kiện thay đổi clipboard windows](https://laptrinhvb.net/uploads/source/csharp/clipboard_thumb.jpg)
![[C#] Selemium Tự động đăng nhập gmail bằng Chrome Driver](https://laptrinhvb.net/uploads/source/image_baiviet/e80088217f18260e628fb7455cad5d09.jpg)
![[C#] Hướng dẫn cách ánh xạ ổ đĩa mạng (Map Disk Network) trong winform](https://laptrinhvb.net/uploads/source/csharp/map_network_csharp_thumb.png)
![[C#] Hướng dẫn khóa màn hình desktop screen lock winform](https://laptrinhvb.net/uploads/source/csharp/lock_screen_csharp.png)

![[C#] Hiển thị phiên bản Net Framework từ file dll hoặc exe](https://laptrinhvb.net/uploads/source/new_image_baiviet/find_netframework_build_csharp.png)
![[C#] Hướng dẫn tạo shortcut nhanh cho ứng dụng  đang chạy](https://laptrinhvb.net/uploads/source/csharp/short_cut_app_windows_thumb.png)
![[C#] Hướng dẫn tạo file PDF sử dụng thư viện QuestPDF](https://laptrinhvb.net/uploads/source/new_image_baiviet/tao_file_pdf.png)
![[C#] Hướng dẫn tạo custom list sử dụng Usercontrol và FlowLayoutPanel](https://laptrinhvb.net/uploads/source/vbnet/custom_list_csharp_thumb.jpg)
![[C#] Khóa, mở khóa, protected file readonly USB trên winform](https://laptrinhvb.net/uploads/source/csharp/usb_management_thumb.png)

![[C#] Hướng dẫn nối nhiều file PDF thành 1 file PDF](https://laptrinhvb.net/uploads/source/image_baiviet/42bc03a10d35047d17dab7425e386c14.jpg)

![[C#] Hướng dẫn hiện thị progress bar window khi copy file hoặc folder sử dụng thư viện visualbasic](https://laptrinhvb.net/uploads/source/image_baiviet/2017a10730b82d5561a3b1931e71befe.jpg)
![[C#] Hướng dẫn ghi file trực tiếp excel sử dụng RTD (Real Time Data) Server](https://laptrinhvb.net/uploads/source/csharp/realtime_excel_csharp_thumb.jpg)
![[C#] Hiển thị cửa sổ user consent trên winform NET Core 6](https://laptrinhvb.net/uploads/source/new_image_baiviet/user_consent_csharp.gif)
![[C#] Hướng dẫn viết ứng dụng Fake IP (ẩn IP) sử dụng HttpRequest trong lập trình csharp](https://laptrinhvb.net/uploads/source/csharp/fake_ip_thumb.jpg)
![[C#] Hướng dẫn tạo control động đơn giản trong Csharp](https://laptrinhvb.net/uploads/source/image_baiviet/3e6856446ede19b79fcd520b73223851.png)
![[C# - Console] - Tạo ứng dụng đơn giản Lấy random Item theo Phần trăm xuất hiện](https://laptrinhvb.net/uploads/source/csharp/WhatstheDeal.png)
![[C#] Hướng dẫn Flip Image Winform](https://laptrinhvb.net/uploads/source/csharp/flip_Image_csharp.gif)
![[C#] Hướng dẫn tạo hiệu ứng text Fake Typer Effect Winform](https://laptrinhvb.net/uploads/source/csharp/autoTyper_demo.gif)
