Unity excel配置表导出工具
发表于2019-01-24
下面给大家分享的工具,主要用于把excel导出为二进制文件,供游戏读。






使用方法
将ExcelTools放在项目Assets文件夹中
创建配置表:

同一张表中可以有多个工作簿,第一行为注释,程序中不会读取,第二行为字段名,之后为内容。
制作好配置表后放入Asset/ExcelTools/xlsx文件夹中。
然后在ExcelTools/GameData/ConfigClass.cs中创建相应的配置表类,类名要与相应的配置表工作薄的名称相同,上面的表中就是ExcelATest1,ExcelATest2.
[Serializable] public class ExcelATest1 : ConfigClass { public string id; public string eat1_1; public string eat1_2; public int eat1_3; } [Serializable] public class ExcelATest2 : ConfigClass { public string id; public string eat2_1; public string eat2_2; public int eat2_3; }
注意所有的配置表类需要加上[Serializable]。
之后需要创建存放导出的配置文件的文件夹,StreamingAssets/Config
然后点击菜单栏中的[配置表工具/生成配置表]

之后会看到文件选择窗口,窗口中会列出Asset/ExcelTools/xlsx中的全部文件

选择我们想要导出的配置表,如果没有问题,我们将看到导出成功的提示

这里会列出所有导出成功的工作薄,这时我们就可以在StreamingAssets/Config中看到我们的配置文件了

由于二进制文件使用起来比较方便,而且体积小,所以这里采用二进制文件来保存,如果不想用二进制,还可以使用xml等方式来存储,反正从excel读取出来都存在list里面,想怎么存储都很随意。
由于我们导出的是二进制文件,所以只能放在StreamingAssets文件夹下,并且使用的时候需要使用www的方式来加载。
项目中用一个测试脚本来测试数据:
using System.Collections; using System.Collections.Generic; using UnityEngine; using LitJson; public class ReadTest : MonoBehaviour { //key:表名 val 表数据列表 Dictionary<string, List<ConfigClass>> dic = new Dictionary<string, List<ConfigClass>>(); int loadStep = 0; private void Start() { StartCoroutine(ReadConfigFile("ExcelATest1.msconfig")); StartCoroutine(ReadConfigFile("ExcelATest2.msconfig")); StartCoroutine(ReadConfigFile("ExcelBTest1.msconfig")); } void LogData(){ Debug.Log(JsonMapper.ToJson(dic["ExcelATest1.msconfig"][0])); Debug.Log(JsonMapper.ToJson(dic["ExcelATest1.msconfig"][1])); Debug.Log(JsonMapper.ToJson(dic["ExcelATest1.msconfig"][2])); } IEnumerator ReadConfigFile(string filename) { loadStep++; string filepath = ExcelTool.GetConfigFilePath(filename); WWW www = new WWW(filepath); yield return www; while (www.isDone == false) yield return null; if (www.error == null) { byte[] data = www.bytes; List<ConfigClass> datalist = (List<ConfigClass>)ExcelTool.DeserializeObj(data); dic.Add(filename,datalist); } else { //GameLogTools.SetText("wwwError<<" + www.error + "<<" + filepath); Debug.Log("wwwError<<" + www.error + "<<" + filepath); } loadStep--; if(loadStep <= 0){ LogData(); } } }
将脚本挂到游戏物体上并运行场景,可以看到控制台的输出:

接下来就可以在我们的程序中使用这些数据了。
项目地址:https://github.com/LiuFeng1011/Test/tree/master/Assets/ExcelTools