Unity讀取Excel檔案轉換XML格式檔案
阿新 • • 發佈:2020-06-22
本文例項為大家分享了Unity讀取Excel檔案轉換XML格式檔案的具體程式碼,供大家參考,具體內容如下
此方法用到excel.dll
下載連線點選開啟連結
using System.Collections.Generic; using UnityEngine; using System.IO; using System.Xml; using Excel; using System.Data; /// <summary> /// 建立XML表 /// </summary> public class CreateXML : MonoBehaviour { /// <summary> /// 表頭 /// </summary> public const string xmlRoot = "FZW_MASK_XML_TABLE"; //Excel名字 public string ExcelPathName; //xml檔案路徑; private string Path; //表文件名 public string xmlName = "XMLTABLE.xml"; //表名 public string xmlTabeName = "XMLTABLE"; //第一行欄位 private string[] tableTop; //表List private List<string[]> tableList=new List<string[]>(); private void Awake() { //設定路徑 Path = Application.streamingAssetsPath + "/XMLTable/" + xmlName; //讀取Excel ReadExcel(ExcelPathName); } /// <summary> /// 讀Excel /// </summary> /// <param name="ExcelPath"></param> /// <returns></returns> public void ReadExcel(string ExcelPath) { //excel檔案位置 /MaskGame/ReadExcel/excel檔名 FileStream stream = File.Open(Application.dataPath + "/MaskGame/ReadExcel/" + ExcelPath,FileMode.Open,FileAccess.Read); IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream); DataSet result = excelReader.AsDataSet(); int rows = result.Tables[0].Rows.Count;//獲取行數(多少行資訊) int columns = result.Tables[0].Columns.Count;//獲取列數(多少列欄位) //初始化欄位 tableTop = new string[columns]; //存欄位 for (int i = 0; i < columns; i++) { tableTop[i]= result.Tables[0].Rows[0][i].ToString(); } //從第二行開始讀 讀資訊 for (int i = 1; i < rows; i++) { //臨時表 string[] table = new string[columns]; //賦值表資訊 for (int j = 0; j < columns; j++) { string nvalue = result.Tables[0].Rows[i][j].ToString(); table[j] = nvalue; } //新增到List tableList.Add(table); } } /// <summary> /// 建立表格 /// </summary> private void CreateXMLTable() { //路徑錯誤 if (File.Exists(Path)) return; //xml物件; XmlDocument xmll = new XmlDocument(); //跟節點 XmlElement Root = xmll.CreateElement(xmlRoot); for (int i = 0; i < tableList.Count; i++) { XmlElement xmlElement = xmll.CreateElement(xmlTabeName); xmlElement.SetAttribute(tableTop[0],tableList[i][0]); for (int j = 0; j < tableTop.Length-1; j++) { XmlElement infoElement = xmll.CreateElement(tableTop[j + 1]); infoElement.InnerText = tableList[i][j + 1]; xmlElement.AppendChild(infoElement); } Root.AppendChild(xmlElement); } xmll.AppendChild(Root); xmll.Save(Path); } void OnGUI() { if (GUI.Button(new Rect(200,200,500,500),"建立XML表")) { CreateXMLTable(); Debug.Log("建立成功: " + Path); } } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。