这篇文章主要为大家详细介绍了Unity读取Excel文件转换XML格式文件,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
本文实例为大家分享了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);
}
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持得得之家。
织梦狗教程
本文标题为:Unity读取Excel文件转换XML格式文件


基础教程推荐
猜你喜欢
- C#通过标签软件Bartender的ZPL命令打印条码 2023-05-16
- C#中 Json 序列化去掉null值的方法 2022-11-18
- C#中的Linq to JSON操作详解 2023-06-08
- Unity 如何获取鼠标停留位置下的物体 2023-04-10
- C# 解析XML和反序列化的示例 2023-04-14
- 实例详解C#实现http不同方法的请求 2022-12-26
- C#调用摄像头实现拍照功能的示例代码 2023-03-09
- Unity shader实现高斯模糊效果 2023-01-16
- C#获取指定目录下某种格式文件集并备份到指定文件夹 2023-05-30
- c# – USING块在网站与Windows窗体中的行为不同 2023-09-20