欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Unity Excel转XML

程序员文章站 2024-03-18 17:45:28
...
using Excel;
using System.Data;
using System.IO;
using System.Xml;
using UnityEditor;
using UnityEngine;

public class ExcelToXml : EditorWindow
{
    public string excelPath;
    public string xmlName;

    [MenuItem("文本格式转换/Excel转XML")]
    public static void SetWindow()
    {
        EditorWindow.GetWindow(typeof(ExcelToXml));
    }

    private void OnGUI()
    {
        excelPath = EditorGUILayout.TextField("excel文件路径", excelPath);
        xmlName = EditorGUILayout.TextField("xml文件名", xmlName);
        if (GUILayout.Button("Excel转XML") && excelPath != "")
        {
            TranslateFromat();
        }
    }

    private void TranslateFromat()
    {
        DataTable excelData = GetDataset(Application.streamingAssetsPath + "/ExcelConfig/" + excelPath + ".xlsx").Tables[0];

        ToXml(xmlName, excelData, "root", "UIData", new string[] { "Description", "UnityName", "SignalName" });
    }

    public DataSet GetDataset(string path)
    {
        FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read);
        IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(fs);
        DataSet ds = excelReader.AsDataSet();
        fs.Dispose();
        return ds;
    }

    /// <summary>
    /// 将dataset数据根据字符串索引进行xml序列化
    /// </summary>
    /// <param name="xmlname"></生成的xml名字>
    /// <param name="DT"></dataset的table>
    /// <param name="strAtt"></父节点序列>
    /// <param name="middlelement"></中间级子节点序列>
    /// <param name="strelement"></子节点序列>
    public void ToXml(string xmlname, DataTable DT, string strAtt, string middlelement, string[] strelement)
    {
        if (DT != null)
        {
            if (DT.Rows.Count > 0)
            {
                if (!Directory.Exists(Application.streamingAssetsPath))
                {
                    Directory.CreateDirectory(Application.streamingAssetsPath);
                }
                string path = Application.streamingAssetsPath + "/" + xmlname + ".xml";
                if (File.Exists(path))
                {
                    File.Delete(path);
                }
                XmlDocument writer = new XmlDocument();
                XmlElement root = writer.CreateElement(strAtt);
                for (int i = 0; i < DT.Rows.Count; i++)
                {
                    XmlElement middleRoot = writer.CreateElement(middlelement);
                    for (int j = 0; j < strelement.Length; j++)
                    {
                        XmlElement element = writer.CreateElement(strelement[j]);
                        element.InnerText = DT.Rows[i][j].ToString();
                        middleRoot.AppendChild(element);

                    }
                    root.AppendChild(middleRoot);
                }
                writer.AppendChild(root);
                writer.Save(path);
            }
        }
    }
}