unity打开excel表格_Unity读取Excel文件转换XML格式文件

本文介绍如何在Unity中使用C#读取Excel文件并将其内容转换为XML格式。通过创建一个名为`CreateXML`的类,演示了读取Excel表格,解析数据并保存为XML文件的过程。在Unity的OnGUI方法中,提供了一个按钮来触发XML的创建,创建成功后在控制台输出路径。
摘要由CSDN通过智能技术生成

本文实例为大家分享了Unity读取Excel文件转换XML格式文件的具体代码,供大家参考,具体内容如下

下载连接 点击打开链接

using System.Collections.Generic;

using UnityEngine;

using System.IO;

using System.Xml;

using Excel;

using System.Data;

///

/// 创建XML表

///

public class CreateXML : MonoBehaviour

{

///

/// 表头

///

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 tableList=new List();

private void Awake()

{

//设置路径

Path = Application.streamingAssetsPath + "/XMLTable/" + xmlName;

//读取Excel

ReadExcel(ExcelPathName);

}

///

/// 读Excel

///

///

///

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);

}

}

///

/// 创建表格

///

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);

}

}

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值