从策划配置文件导入项目实际使用,为提高效率总会使用一些转换工具,据同事介绍Epplus更强大一些,我自己试了下,发现api非常全面且强大。记录下所学。
一、插件来源
https://github.com/JanKallman/EPPlus
https://www.nuget.org/packages/EPPlus/
二、使用
在其github的WiKi页签有简单的使用示例, 具体导成什么格式,看自己的项目需求了。我是转成.asset和json格式的。
2.1 配置excel
我分了两个sheet:
2.2 设计对应的数据结构
我使用的 jsonUtility.fromjson 不支持ScriptableObject,所以写了两个结构。
- [Serializable]
- public class SurfaceTile
- {
- public int ID;
- public int Layer;
- public string SpriteName;
- public string Vertices;
- }
- [Serializable]
- public class BuildingTile
- {
- public int ID;
- public string SpriteName;
- public int GridWidth;
- public int GridHeight;
- public int Interactive;
- }
- public class MapTileConfig : ScriptableObject
- {
- public List<SurfaceTile> BasicTileData;
- public List<BuildingTile> BuildingData;
- }
- public class MapTileConfigForJson
- {
- public List<SurfaceTile> BasicTileData;
- public List<BuildingTile> BuildingData;
- }
2.3 解析
2.3.1 .asset解析
为了减少解析过程与数据结构的耦合, 我将sheet名设置为数据结构名, 利用反射来获取类型与创建实例
- static Type GetType(string typeName)
- {
- Type type = null;
- Assembly curExecuteAssembly = Assembly.GetExecutingAssembly();
- AssemblyName[] refAssembly = curExecuteAssembly.GetReferencedAssemblies();
- foreach (var assemblyName in refAssembly)
- {
- var assembly = Assembly.Load(assemblyName);
- if(assemblyName != null)
- {
- type = assembly.GetType(typeName);
- if (type != null)
- break;
- }
- }
- //typeof(SurfaceTile).Assembly.GetType()
- return type;
- }
- var dataObj = dataType.Assembly.CreateInstance(sheet.Name);
我使用的 List<List<object>> excelData 来临时保存excel数据,但在数据转换为 MapTileConfig 类型没想到好的处理方式。希望有想法的可以指导下。
- static void SettingToAsset(List<List<object>> data, string assetPath)
- {
- MapTileConfig mapConfig = ScriptableObject.CreateInstance<MapTileConfig>();
- for (int i = 0; i < data[0].Count; i++)
- {
- mapConfig.BasicTileData.Add((SurfaceTile)data[0][i]);
- }
- for (int i = 0; i < data[1].Count; i++)
- {
- mapConfig.BuildingData.Add((BuildingTile)data[1][i]);
- }
- AssetDatabase.CreateAsset(mapConfig, testAssetPath + "/MapTileConfig.asset");
- AssetDatabase.SaveAssets();
- }
2.3.2 json解析
只要按着json格式,将键值对对应好,解析是很容易的,唯一没想明白的是jsonUtility.fromjson竟然不支持ScriptableObject结构。
三、总结
因大量的逻辑代码都是用的lua,所以excel解析成json或直接lua形式的数据,都是比较方便的。
有兴趣的可以查看我的测试代码:https://github.com/feixus/UnityTools