不支持数组,字典等集合数据结构,可额外修改。Newtonsoft以及epplus要事先加载进unity中。
设计为一张表格,多个sheet。
/* 一张xlsx里面有多张表格,因为实际游戏中使用的是json文件,所以生成的时候我只用一张xlsx
* 一张sheet就是一个数据集合
* 根据sheet表字段生成对应的数据集合json
* 创建json文件同时创建实体类
*/
public class ExcelWindow : EditorWindow
{
private string txt_ExcelName = "tab1.xlsx"; //表格名称
private string txt_JsonSavePath = "Json";
private string txt_EntitySavePath = "Entity";
private Vector2 scrollPos;
[MenuItem("Window/ExcelToJson")]
static void OpenWindow()
{
ExcelWindow window = (ExcelWindow)EditorWindow.GetWindow(typeof(ExcelWindow));
window.Show();
}
private void OnGUI()
{
scrollPos = EditorGUILayout.BeginScrollView(scrollPos);
EditorGUILayout.BeginHorizontal();
GUILayout.Label("表格名称: ");
txt_ExcelName = GUILayout.TextField(txt_ExcelName);
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
GUILayout.Label("Json保存路径: ");
txt_JsonSavePath = GUILayout.TextField(txt_JsonSavePath);
EditorGUILayout.EndHorizontal();
if (GUILayout.Button("生成实体类"))
{
CreateEntities();
}
if (GUILayout.Button("生成Json"))
{
ExcelToJson();
}
EditorGUILayout.EndScrollView();
}
private void ExcelToJson()
{
if (!string.IsNullOrEmpty(txt_ExcelName))
{
string filepath = Application.dataPath + "/" + txt_ExcelName;
string headPath = $"{Application.dataPath}/{txt_JsonSavePath}";
using (FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read))
{
using (ExcelPackage ep = new ExcelPackage(fs))
{
//获得所有工作表
ExcelWorksheets workSheets = ep.Workbook.Worksheets;
List<System.Object> lst = new List<object>();
//遍历所有工作表
for (int i = 1; i <= workSheets.Count; i++)
{
//当前工作表
ExcelWorksheet sheet = workSheets[i];
//初始化集合
lst.Clear();
int columnCount = sheet.Dimension.End.Column;
int rowCount = sheet.Dimension.End.Row;
//根据实体类创建对象集合序列化到json中
for (int z = 4; z <= rowCount; z++)
{
Assembly ab = Assembly.Load("Assembly-CSharp"); //要注意对面在那个程序集里面dll
Type type = ab.GetType($"Entity.{sheet.Name}");
if(type==null)
{
Debug.LogError("你还没有创建对应的实体类!");
return;
}
if (!Directory.Exists(headPath))
Directory.CreateDirectory(headPath);
object o = ab.CreateInstance(type.ToString());
for (int j = 1; j <= columnCount; j++)
{
FieldInfo fieldInfo = type.GetField(sheet.Cells[i, j].Text); //先获得字段信息,方便获得字段类型
object value = Convert.ChangeType(sheet.Cells[z, j].Text, fieldInfo.FieldType);
type.GetField(sheet.Cells[1, j].Text).SetValue(o, value);
}
lst.Add(o);
}
//写入json文件
string jsonPath = $"{headPath}/{sheet.Name}.json";
if (!File.Exists(jsonPath))
{
File.Create(jsonPath).Dispose();
}
File.WriteAllText(jsonPath, JsonConvert.SerializeObject(lst));
}
}
}
AssetDatabase.Refresh();
}
}
void CreateEntities()
{
if (!string.IsNullOrEmpty(txt_ExcelName))
{
string filepath = Application.dataPath + "/" + txt_ExcelName;
using (FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read))
{
using (ExcelPackage ep = new ExcelPackage(fs))
{
//获得所有工作表
ExcelWorksheets workSheets = ep.Workbook.Worksheets;
//遍历所有工作表
for (int i = 1; i <= workSheets.Count; i++)
{
CreateEntity(workSheets[i]);
}
AssetDatabase.Refresh();
}
}
}
}
void CreateEntity(ExcelWorksheet sheet)
{
string dir = $"{Application.dataPath}/{txt_EntitySavePath}";
string path = $"{dir}/{sheet.Name}.cs";
StringBuilder sb = new StringBuilder();
sb.AppendLine("namespace Entity");
sb.AppendLine("{");
sb.AppendLine($"\tpublic class {sheet.Name}");
sb.AppendLine("\t{");
//遍历sheet首行每个字段描述的值
Debug.Log("column = " + sheet.Dimension.End.Column);
Debug.Log("row = " + sheet.Dimension.End.Row);
for (int i = 1; i <= sheet.Dimension.End.Column; i++)
{
sb.AppendLine("\t\t/// <summary>");
sb.AppendLine($"\t\t///{sheet.Cells[3, i].Text}");
sb.AppendLine("\t\t/// </summary>");
sb.AppendLine($"\t\tpublic {sheet.Cells[2, i].Text} {sheet.Cells[1, i].Text};");
}
sb.AppendLine("\t}");
sb.AppendLine("}");
try
{
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
if (!File.Exists(path))
{
File.Create(path).Dispose(); //避免资源占用
}
File.WriteAllText(path, sb.ToString());
}
catch (System.Exception e)
{
Debug.LogError($"Excel转json时创建对应的实体类出错,实体类为:{sheet.Name},e:{e.Message}");
}
}
}