上一篇文章讲了如何用ExcelManager解析Excel文件,本篇需要与上一篇链接内容结合使用,链接Unity:通过ExcelManager类将Excel中的内容解析为字符串二维数组(适用于Windows)_unity 将excel表的数据转为字符串_努力长头发的程序猿的博客-CSDN博客
ExcelManager解析数据在PC上可以用,但是安卓上时行不通的,所以需要吧Excel转换成Json文件在对Json文件进行读取操作
首先是利用继承了UnityEditor类的JosnEditor类生成菜单,然后在Assets目录下创建Resources文件夹里面创建Json文件夹,点击生成出来的Json菜单并点击转换,就可以把Assets目录下Excel文件夹内的全部文件转化为同名Json文件保存到Asstes/Resources/Json目录下(继承了UnityEditor类的脚本必须要放在名为Editor的文件夹下,否则导出项目时会报错,如果没有Editor文件夹就在Asstes目录下自己创建一个)
using UnityEngine;
using UnityEditor;
using System.IO;
using LitJson;
public struct Json_Save_Value
{
public int x,y;
public string[,] str;
}
public class JsonEditor : MonoBehaviour
{
private static Json_Save_Value _jsonSaveValue;
[MenuItem("Json/转换")]
public static void Excel_Change_Json()
{
string [] str = Directory.GetFiles(Application.dataPath + "/Excel/", "*.xlsx");
for (int i = 0; i < str.Length; i++)
{
string strr = str[i];
strr = strr.Replace(Application.dataPath + "/Excel/", "");
strr = strr.Replace(".xlsx", "");
ExcelManager.Main.GetExcel(strr, SetJosn);
}
}
private static void SetJosn(string[,] str,string name)
{
_jsonSaveValue.str = str;
_jsonSaveValue.x = str.GetLength(0);
_jsonSaveValue.y = str.GetLength(1);
string a = JsonMapper.ToJson(_jsonSaveValue);
StreamWriter write = new StreamWriter(Application.dataPath +"/Resources/Json/"+name+".txt");
write.Write(a);
write.Close();
}
}
然后是JsonManager类,C#单例类不需要挂载到场景,调用GetExvel读取Resources下Json文件夹中的参数一名字的Json文件,在读取完毕后调用参数二的回调函数
using System;
using UnityEngine;
using LitJson;
public struct Json_Load_Value
{
public int x,y;
public string[] str;
}
public class JsonManager
{
private static JsonManager main;
public static JsonManager Main
{
get
{
if (main == null)
{
main = new JsonManager();
}
return main;
}
}
private Json_Load_Value _jsonLoadValue;
public void GetExcel(string path, Action<int,int,string[,]> action)
{
GetJosn(path);
string [,] str = new string[_jsonLoadValue.x,_jsonLoadValue.y];
for (int i = 0; i < _jsonLoadValue.x; i++)
{
for (int j = 0; j < _jsonLoadValue.y; j++)
{
str[i, j] = _jsonLoadValue.str[j + i * _jsonLoadValue.y];
}
}
action(_jsonLoadValue.x,_jsonLoadValue.y,str);
}
private void GetJosn(string path)
{
string a = Resources.Load<TextAsset>("Json/" + path).text;
_jsonLoadValue = JsonMapper.ToObject<Json_Load_Value>(a);
}
}