Unity导表工具-excel文件转json

Unity导表工具-excel文件转json


导表工具意在让策划可以方便的修改大量数据而不依赖程序。在项目初期程序要定义各种数据结构,并且与策划约定好表的格式,就可以开始做导表工具了。程序呢可以把这个工具做的更灵活些,这样以后对表的增删改查或者应对不同的表也能很方便。

数据结构定义:

    [System.Serializable]
    public class HeroBaseData
    {
        public string heroName;
        public float heroHP;
        public float moveSpeed;
        public float chargeCD;
        public float defenseValue;
        public int[] skillList;
    }

表格规定:

  1. 表格第一行表示该列的描述;
  2. 表格第二行表示对应的数据结构里的名称;
  3. 表格第三行是该列的数据格式;
  4. 多个数值用’,’分开。

下面就可以做工具了,在这之前准备一些第三方插件导入到Unity项目中:

  1. ExcelDataReader :http://exceldatareader.codeplex.com/
  2. System.data.dll,在unity安装路径下的Editor\Data\Mono\lib\mono\unity;
  3. Newtonsoft.Json:https://www.newtonsoft.com/json

代码:

using Excel;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Reflection;
using UnityEditor;
/// <summary>
/// xlsc->Json 需要引入Excel和NetworkJson插件
/// </summary>
public class XLSXToJson
{
    [MenuItem("XLSX/ToJson")]
    public static void DoXlsxToJson()
    {
        string dataPath = UnityEngine.Application.dataPath;
        // xlsx路径
        string xlsxPath = string.Format("{0}Xlsx/BaseData.xlsx", dataPath.Remove(dataPath.IndexOf("Assets")));
        // xlsx工作表名名
        string[] SheetNames = { "ALLHeros" };
        FileStream stream = null;
        try
        {
            stream = File.Open(xlsxPath, FileMode.Open, FileAccess.Read);
        }
        catch (IOException e)
        {
            UnityEngine.Debug.LogFormat("关闭xlsx文件后重试!");
        }
        if (stream == null)
            return;
        IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
        DataSet result = excelReader.AsDataSet();
        UnityEngine.Debug.Log(result.DataSetName);
        // 读取第一张工资表
        ReadSingleSheet(typeof(HeroBaseData), result.Tables[SheetNames[0]], string.Format("{0}/{1}.json", UnityEngine.Application.streamingAssetsPath, SheetNames[0]));
        UnityEngine.Debug.Log("保存完成!");
    }
    /// <summary>
    /// 读取一个工作表的数据
    /// </summary>
    /// <param name="type">要转换的struct或class类型</param>
    /// <param name="dataTable">读取的工作表数据</param>
    /// <param name="jsonPath">存储路径</param>
    private static void ReadSingleSheet(Type type, DataTable dataTable, string jsonPath)
    {
        int rows = dataTable.Rows.Count;
        int Columns = dataTable.Columns.Count;
        // 工作表的行数据
        DataRowCollection collect = dataTable.Rows;
        // xlsx对应的数据字段,规定是第二行
        string[] jsonFileds = new string[Columns];
        // 要保存成Json的obj
        List<object> objsToSave = new List<object>();
        for (int i = 0; i < Columns; i++)
        {
            jsonFileds[i] = collect[1][i].ToString();
        }
        // 从第三行开始
        for (int i = 3; i < rows; i++)
        {
            // 生成一个实例
            Object objIns = type.Assembly.CreateInstance(type.ToString());

            for (int j = 0; j < Columns; j++)
            {
                // 获取字段
                FieldInfo field = type.GetField(jsonFileds[j]);
                if (field != null)
                {
                    object value = null;
                    try // 赋值
                    {
                        value = Convert.ChangeType(collect[i][j], field.FieldType);
                    }
                    catch (InvalidCastException e) // 一般到这都是Int数组,当然还可以更细致的处理不同类型的数组
                    {
                        Console.WriteLine(e.Message);
                        string str = collect[i][j].ToString();
                        string[] strs = str.Split(',');
                        int[] ints = new int[strs.Length];
                        for (int k = 0; k < strs.Length; k++)
                        {
                            ints[k] = int.Parse(strs[k]);
                        }
                        value = ints;
                    }
                    field.SetValue(objIns, value);
                }
                else
                {
                    UnityEngine.Debug.LogFormat("有无法识别的字符串:{0}", jsonFileds[j]);
                }
            }
            objsToSave.Add(objIns);
        }
        // 保存为Json
        string content = Newtonsoft.Json.JsonConvert.SerializeObject(objsToSave);
        SaveFile(content, jsonPath);
    }

    private static void SaveFile(string content, string jsonPath)
    {
        StreamWriter streamWriter;
        FileStream fileStream;
        if (File.Exists(jsonPath))
        {
            File.Delete(jsonPath);
        }
        fileStream = new FileStream(jsonPath, FileMode.Create);
        streamWriter = new StreamWriter(fileStream);
        streamWriter.Write(content);
        streamWriter.Close();
    }
}

转换后的Json文件:

转化成json之后,我们代码里就可以直接使用json了:

    public static List<T> JsonToObj<T>(string strPath)
    {
        return (List<T>)JsonConvert.DeserializeObject(ReadStringInfo(strPath), typeof(List<T>));
    }

不只是json,同理我们可以把excel转化成其他想要的格式,还可以进行加密。

猜你喜欢

转载自blog.csdn.net/Teddy_k/article/details/81191049