做unity 项目也有一段时间了,从unity项目开发和学习中也遇到了很多坑,并且也从中学习到了很多曾经未接触的领域。项目中的很多功能模块,从今天开始把自己的思路和代码奉上给学渣们作为一份学习的资料。如果学长们看到哪里写的不好欢迎吐槽并给予更好的解决方案。好了话也不多说了今天给大家亮出的是excel 数据解析和在unity项目中的应用。

*导入excel,解析xml,生成c#数据表,生成asset数据文件
 *原理 在导入xml文件的时候通过XmlReader读取xml文件
 *把需要的内容按照读取的顺序保存,然后在生成key,最后生成key,value格式,然后自己手动定义要保存的内容数据格式最后通过自定义的数据格式生成数据文件

注:ExcelControl 这个类必须放在Editor目录下
using UnityEngine;
using System.Collections;
using UnityEditor;
using System.Xml;
using System;
using System.Collections.Generic; public class ExcelControl : AssetPostprocessor
{
static string FILE_PATH = "Assets\\Data\\"; /** 在导入所有资源之后 */
static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
{ string excelPath = "";
for (int i = ; i < importedAssets.Length; i++)
{
/** 拦截Assets/Excel目录下面所有.xml文件进行解析 */
excelPath = importedAssets[i];
if (excelPath.Contains(".xml"))
{
ReadXml(excelPath);
Debug.Log("Excel import asset path : " + excelPath);
}
}
} static void ReadXml(string xmlPath)
{
/** 读取xml 文件 */
XmlReader xReader = null;
try
{
xReader = XmlReader.Create(xmlPath);
}
catch (Exception e)
{
Debug.LogError("Read Excel Error! Path = " + xmlPath);
}
if (xReader == null)
{
return;
} /** 保存所有数据到表中 */
List<xmlSheetList> xmlDataList = new List<xmlSheetList>();
xmlSheetList xsl = null; /** 记录每个节点的开始 */
bool sheetBegin = false;
bool rowBegin = false;
bool cellBegin = false;
bool dataBegin = false; /** 行数 */
int rowNum = ;
/** 列数 */
int cellNum = ;
/** 计数器 */
int num = ;
while (xReader.Read())
{
string name = xReader.Name; if (name == "Worksheet")
{
/** 开始 */
if (xReader.NodeType == XmlNodeType.Element)
{
sheetBegin = true;
/** xmlSheet */
xsl = new xmlSheetList();
xsl.Clear();
}
/** 结束 */
else if (xReader.NodeType == XmlNodeType.EndElement)
{
sheetBegin = false;
xmlDataList.Add(xsl);
}
}
else if (name == "Row")
{
/** 开始 */
if (xReader.NodeType == XmlNodeType.Element)
{
rowBegin = true;
rowNum++;
}
/** 结束 */
else if (xReader.NodeType == XmlNodeType.EndElement)
{
rowBegin = false;
}
}
else if (name == "Cell")
{
/** 开始 */
if (xReader.NodeType == XmlNodeType.Element)
{
cellBegin = true;
if (rowNum == )
{
cellNum++;
}
if (!string.IsNullOrEmpty(xReader.GetAttribute("ss:Index")))
{ Debug.LogError(string.Format("xml read error! may be empty! : {0} Row = {1} Cell = {2}.", xmlPath, (int)(num / cellNum), ((num % cellNum) + )));
return;
}
}
/** 结束 */
else if (xReader.NodeType == XmlNodeType.EndElement)
{
cellBegin = false;
}
}
else if (name == "Data")
{
/** 开始 */
if (xReader.NodeType == XmlNodeType.Element)
{
dataBegin = true;
}
/** 结束 */
else if (xReader.NodeType == XmlNodeType.EndElement)
{
dataBegin = false;
}
}
else {
/** 过滤数据 */
if (sheetBegin && rowBegin && cellBegin && dataBegin)
{
num++;
if (xsl != null)
{
xsl.Add(xReader.Value);
}
}
}
}
int an = xmlDataList.Count; //生成key列表
List<string> keys = new List<string>();
for (int i = ; i < xmlDataList.Count; i++)
{
for (int k = ; k < cellNum; k++)
{
if (k < cellNum)
{
keys.Add(xmlDataList[i].sheetList[]);
// 删除原始列表中key的数据
xmlDataList[i].sheetList.RemoveAt();
}
else {
break;
}
}
} // 创建key 和 value 结构
List<Row> rowList = new List<Row>();
int nb = ;
for (int k = ; k < xmlDataList.Count; k++)
{
nb = xmlDataList[k].sheetList.Count / cellNum;
for (int i = ; i < nb; i++)
{
Row row = new Row();
row._key = keys;
for (int j = ; j < cellNum; j++)
{
row._cells.Add(xmlDataList[k].sheetList[]);
xmlDataList[k].sheetList.RemoveAt();
}
rowList.Add(row);
}
}
/** 创建资源 */
CreatXmlListAsset(rowList, xmlPath);
} /** 生成数据文件 */
static void CreatXmlListAsset(List<Row> rl, string xmlPath)
{
if (xmlPath.Contains("excel.xml"))
{
//新生成的数据
ExcelDataList dataList = null; //检查是否已经声称过了数据表
UnityEngine.Object oldFile = AssetDatabase.LoadAssetAtPath(xmlPath, typeof(ExcelDataList));
bool newFile = false;
if (oldFile)
{
dataList = oldFile as ExcelDataList;
}
else {
dataList = new ExcelDataList();
newFile = true;
}
//清空已有数据
dataList.Datalist.Clear(); //生成数据
for (int i = ; i < rl.Count; i++)
{
ExcelData newData = new ExcelData();
Row data = rl[i];
newData.id = GetInt(data["ID"]);
newData.name = data["Name"];
dataList.Datalist.Add(newData);
} // 创建数据文件
if (newFile)
{
AssetDatabase.CreateAsset(dataList, FILE_PATH + "ExcelDataList.asset");
}
else {
EditorUtility.SetDirty(dataList);
}
}
} static int GetInt(string data)
{
float val = ;
try
{
val = float.Parse(data);
}
catch (Exception e)
{
Debug.LogError(e.Message + " data[" + data + "]");
}
return Mathf.RoundToInt(val);
} static float GetFloat(string data)
{
float val = ;
try
{
val = float.Parse(data);
}
catch (Exception e)
{
Debug.LogError(e.Message + " data[" + data + "]");
}
return val;
} static bool GetBool(string data)
{
int val = ;
try
{
val = int.Parse(data);
}
catch (Exception e)
{
Debug.LogError(e.Message + " data[" + data + "]");
}
return val == ? false : true;
}
} /** xmlsheel所有字符串数据 */
public class xmlSheetList
{
public List<string> sheetList = new List<string>(); public void Add(string str)
{
sheetList.Add(str);
} public void Clear()
{
sheetList.Clear();
}
} /** xml (key, Value) Cell */
public class Row
{
public List<string> _cells = new List<string>();
public List<string> _key = new List<string>(); public string this[string key]
{
get
{
string val = "";
int pos = _key.IndexOf(key);
if (pos < || pos >= _cells.Count)
{
Debug.LogError("can't find the value of the key:[" + key + "]");
}
else {
val = _cells[pos];
}
return val;
}
}
}

using UnityEngine;
using System.Collections;
using System.Collections.Generic; [System.Serializable]
public class ExcelData {
public string name = "";
public int id = ;
}
public class ExcelDataList : ScriptableObject {
public List<ExcelData> Datalist = new List<ExcelData>();
}
ExcelData 自定义的数据格式根据项目需求

支持原创,转载请注明作者出处我的博客http://home.cnblogs.com/u/fastHro/

unity 读取excel表 生成asset资源文件的更多相关文章

  1. Unity读取Excel文件(附源代码)

    今天想弄个Unity读取Excel的功能的,发现网上有许多方法,采用其中一种方法:加入库文件 Excel.dll 和ICSharpCode.SharpZipLib.dll库文件,(还有System.D ...

  2. Jmeter读取excel表中用例数据实现接口压测

    传统的接口测试,都是在接口中手动输入不同用例准备的多种场景参数数据,一遍一遍的输入来执行多个不同的用例,但是现在利用excel表格准备各种类型的数据,使用Jmeter中Jmeter CSV Data ...

  3. Python xlrd模块读取Excel表中的数据

    1.xlrd库的安装 直接使用pip工具进行安装(当然也可以使用pycharmIDE进行安装,这里就不详述了) pip install xlrd 2.xlrd模块的一些常用命令 ①打开excel文件并 ...

  4. Python+Selenium进行UI自动化测试项目中,常用的小技巧1:读取excel表,转化成字典(dict)输出

    从今天开始我将会把在项目中遇到的问题,以及常用的一些技巧来分享出来,以此来促进自己的学习和提升自己:更加方便我以后的查阅. 现在要说的是:用Python来读取excel表的数据,返回字典(dict), ...

  5. Jar中的Java程序如何读取Jar包中的资源文件

    Jar中的Java程序如何读取Jar包中的资源文件 比如项目的组织结构如下(以idea中的项目为例): |-ProjectName |-.idea/  //这个目录是idea中项目的属性文件夹 |-s ...

  6. 读取web应用下的资源文件(例如properties)

    package gz.itcast.b_resource; import java.io.IOException; import java.io.InputStream; import java.ut ...

  7. Aspose.cells 读取Excel表中的图片问题

    一.说明 本文主要是讲解,怎么使用aspose.cells读取Excel表中的图片,并把图片转换成流或是image对象. 二.开发环境说明 开发工具vs2012,c#语言, 三.Aspose.cell ...

  8. SVG-Android开源库——SVG生成Vector资源文件的编辑预览工具

    Vector矢量图在Android项目中的应用越来越广泛,但是如果你想用Android Studio自带的工具将SVG图片转化成Vector资源文件却是相当麻烦,首先能支持的SVG规范较少,其次操作流 ...

  9. 读取web工程中.properties资源文件的模板代码

    读取web工程中.properties资源文件的模板代码 // 读取web工程中.properties资源文件的模板代码 private void test2() throws IOException ...

随机推荐

  1. C# upnp

    //获取Host Name var name = Dns.GetHostName(); Console.WriteLine("用户:" + name); //从当前Host Nam ...

  2. HTML5和CSS3基础教程(第8版)-读书笔记

    第1章 网页的构造块 一个网页主要包括以下三个部分: n        文本内容(text content):在页面上让访问者了解页面内容的纯文字. n        对其他文件的引用(referen ...

  3. html css一些记录

    1.忽略将页面中的数字识别为电话号码 <meta content="telephone=no" name="format-detection" /> ...

  4. DNA Pairing

    function pair(str) { //return str; var arr = str.split(''); var pait = ''; var result = arr.map(func ...

  5. 用nodej和glub-watcher写的监听go 项目自动编译,很鸡肋

    glub 一般都是很轻量的编译. go太重了,改一小个部分,就编译的话,多数是编译失败. 而且很消耗性能,还没想到完美的优化办法. 暂时用个定时器 监听2秒,停止1秒,如此循环,会减少些 “无效”的编 ...

  6. 【教程】手把手教你如何利用工具(IE9的F12)去分析模拟登陆网站(百度首页)的内部逻辑过程

    [前提] 想要实现使用某种语言,比如Python,C#等,去实现模拟登陆网站的话,首先要做的事情就是使用某种工具,去分析本身使用浏览器去登陆网页的时候,其内部的执行过程,内部逻辑. 此登陆的逻辑过程, ...

  7. 咏南IOCP中间件

    咏南IOCP中间件 特大好消息,咏南中间件系列新增加——咏南IOCP中间件.咏南IOCP中间件完全兼容咏南DATASNAP中间件的远程方法接口. 中间件DELPHI7~DELPHI XE10.1.1都 ...

  8. XE随想4:SuperObject增、删、改

    unit Unit1; interface uses   Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, For ...

  9. ycsb-命令及参数-与生成的负载类型相关

    loadbin/ycsb load mydb -P workloads/workloada -p "mydb.host=127.0.0.1" -p "mydb.port= ...

  10. 【JSP】Tiles框架的基本使用

    Tiles介绍 Tiles 是一种JSP布局框架,主要目的是为了将复杂的jsp页面作为一个的页面的部分机能,然后用来组合成一个最终表示用页面用的,这样的话,便于对页面的各个机能的变更及维护. Tile ...