解析流程:
1. 配置Excel
2. 讀取解析Excel
3. 整理解析到的數據
4. 自動創建對應的C#類,繼承ScriptableObject,聲明變量,保存.cs文件
5. 自動創建ScriptableObject的Asset文件,並賦值,保存Asset文件
6. 在遊戲直接使用ScriptableObject類
優點:
1. 每個Excel對應一個類,使用靈活,對Excel限制少
2. 自動創建C#類,不需要對每個Excel手動寫代碼,Excel修改後重新生成類即可
3. 自動創建ScriptableObject的Asset文件,自動對類字段賦值
4. 數據值直接寫到ScriptableObject裏,方便查看,可以手動修改調整,不需要每次改動都在Excel裏操作
5. 在遊戲內直接調用ScriptableObject類,不需要額外操作
具體操作:
1. 配置Excel
2. 讀取Excel
#if UNITY_EDITOR
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using Excel;
using System.Reflection;
using System;
//Excel中間數據
public class ExcelMediumData
{
//Excel名字
public string excelName;
//Dictionary<字段名稱, 字段類型>,記錄類的所有字段及其類型
public Dictionary<string, string> propertyNameTypeDic;
//List<一行數據>,List<Dictionary<字段名稱, 一行的每個單元格字段值>>
//記錄類的所有字段值,按行記錄
public List<Dictionary<string, string>> allItemValueRowList;
}
public static class ExcelDataReader
{
//Excel第2行對應字段名稱
const int excelNameRow = 2;
//Excel第4行對應字段類型
const int excelTypeRow = 4;
//Excel第5行及以後對應字段值
const int excelDataRow = 5;
//Excel讀取路徑
public static string excelFilePath = Application.dataPath + "/Excel";
//自動生成C#類文件路徑
static string excelCodePath = Application.dataPath + "/Script/Excel/AutoCreateCSCode";
//自動生成Asset文件路徑
static string excelAssetPath = "Assets/Resources/ExcelAsset";
#region --- Read Excel ---
//創建Excel對應的C#類
public static void ReadAllExcelToCode()
{
//讀取所有Excel文件
//指定目錄中與指定的搜索模式和選項匹配的文件的完整名稱(包含路徑)的數組;如果未找到任何文件,則爲空數組。
string[] excelFileFullPaths = Directory.GetFiles(excelFilePath, "*.xlsx");
if (excelFileFullPaths == null || excelFileFullPaths.Length == 0)
{
Debug.Log("Excel file count == 0");
return;
}
//遍歷所有Excel,創建C#類
for (int i = 0; i < excelFileFullPaths.Length; i++)
{
ReadOneExcelToCode(excelFileFullPaths[i]);
}
}
//創建Excel對應的C#類
public static void ReadOneExcelToCode(string excelFileFullPath)
{
//解析Excel獲取中間數據
ExcelMediumData excelMediumData = CreateClassCodeByExcelPath(excelFileFullPath);
if (excelMediumData != null)
{
//根據數據生成C#腳本
string classCodeStr = ExcelCodeCreater.CreateCodeStrByExcelData(excelMediumData);
if (!string.IsNullOrEmpty(classCodeStr))
{
//寫文件,生成CSharp.cs
if (WriteCodeStrToSave(excelCodePath, excelMediumData.excelName + "ExcelData", classCodeStr))
{
Debug.Log("<color=green>Auto Create Excel Scripts Success : </color>" + excelMediumData.excelName);
return;
}
}
}
//生成失敗
Debug.LogError("Auto Create Excel Scripts Fail : " + (excelMediumData == null ? "" : excelMediumData.excelName));
}
#endregion
#region --- Create Asset ---
//創建Excel對應的Asset數據文件
public static void CreateAllExcelAsset()
{
//讀取所有Excel文件
//指定目錄中與指定的搜索模式和選項匹配的文件的完整名稱(包含路徑)的數組;如果未找到任何文件,則爲空數組。
string[] excelFileFullPaths = Directory.GetFiles(excelFilePath, "*.xlsx");
if (excelFileFullPaths == null || excelFileFullPaths.Length == 0)
{
Debug.Log("Excel file count == 0");
return;
}
//遍歷所有Excel,創建Asset
for (int i = 0; i < excelFileFullPaths.Length; i++)
{
CreateOneExcelAsset(excelFileFullPaths[i]);
}
}
//創建Excel對應的Asset數據文件
public static void CreateOneExcelAsset(string excelFileFullPath)
{
//解析Excel獲取中間數據
ExcelMediumData excelMediumData = CreateClassCodeByExcelPath(excelFileFullPath);
if (excelMediumData != null)
{
////獲取當前程序集
//Assembly assembly = Assembly.GetExecutingAssembly();
////創建類的實例,返回爲 object 類型,需要強制類型轉換,assembly.CreateInstance("類的完全限定名(即包括命名空間)");
//object class0bj = assembly.CreateInstance(excelMediumData.excelName + "Assignment",true);
//必須遍歷所有程序集來獲得類型。當前在Assembly-CSharp-Editor中,目標類型在Assembly-CSharp中,不同程序將無法獲取類型
Type type = null;
foreach (var asm in AppDomain.CurrentDomain.GetAssemblies())
{
//查找目標類型
Type tempType = asm.GetType(excelMediumData.excelName + "AssetAssignment");
if (tempType != null)
{
type = tempType;
break;
}
}
if (type != null)
{
//反射獲取方法
MethodInfo methodInfo = type.GetMethod("CreateAsset");
if (methodInfo != null)
{
methodInfo.Invoke(null, new object[] { excelMediumData.allItemValueRowList, excelAssetPath });
//創建Asset文件成功
Debug.Log("<color=green>Auto Create Excel Asset Success : </color>" + excelMediumData.excelName);
return;
}
}
}
//創建Asset文件失敗
Debug.LogError("Auto Create Excel Asset Fail : " + (excelMediumData == null ? "" : excelMediumData.excelName));
}
#endregion
#region --- private ---
//解析Excel,創建中間數據
private static ExcelMediumData CreateClassCodeByExcelPath(string excelFileFullPath)
{
if (string.IsNullOrEmpty(excelFileFullPath))
return null;
excelFileFullPath = excelFileFullPath.Replace("\\", "/");
//讀取Excel
FileStream stream = File.Open(excelFileFullPath, FileMode.Open, FileAccess.Read);
if (stream == null)
return null;
//解析Excel
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
//無效Excel
if (excelReader == null || !excelReader.IsValid)
{
Debug.Log("Invalid excel : " + excelFileFullPath);
return null;
}
//<數據名稱,數據類型>
KeyValuePair<string, string>[] propertyNameTypes = null;
//List<KeyValuePair<數據名稱, 單元格數據值>[]>,所有數據值,按行記錄
List<Dictionary<string, string>> allItemValueRowList = new List<Dictionary<string, string>>();
//每行數據數量
int propertyCount = 0;
//當前遍歷行,從1開始
int curRowIndex = 1;
//開始讀取,按行遍歷
while (excelReader.Read())
{
if (excelReader.FieldCount == 0)
continue;
//讀取一行的數據
string[] datas = new string[excelReader.FieldCount];
for (int j = 0; j < excelReader.FieldCount; ++j)
{
//賦值一行的每一個單元格數據
datas[j] = excelReader.GetString(j);
}
//空行/行第一個單元格爲空,視爲無效數據
if (datas.Length == 0 || string.IsNullOrEmpty(datas[0]))
{
curRowIndex++;
continue;
}
//數據行
if (curRowIndex >= excelDataRow)
{
//數據無效
if (propertyCount <= 0)
return null;
Dictionary<string, string> itemDic = new Dictionary<string, string>(propertyCount);
//遍歷一行裏的每個單元格數據
for (int j = 0; j < propertyCount; j++)
{
//判斷長度
if (j < datas.Length)
itemDic[propertyNameTypes[j].Key] = datas[j];
else
itemDic[propertyNameTypes[j].Key] = null;
}
allItemValueRowList.Add(itemDic);
}
//數據名稱行
else if (curRowIndex == excelNameRow)
{
//以數據名稱確定每行的數據數量
propertyCount = datas.Length;
if (propertyCount <= 0)
return null;
//記錄數據名稱
propertyNameTypes = new KeyValuePair<string, string>[propertyCount];
for (int i = 0; i < propertyCount; i++)
{
propertyNameTypes[i] = new KeyValuePair<string, string>(datas[i], null);
}
}
//數據類型行
else if (curRowIndex == excelTypeRow)
{
//數據類型數量少於指定數量,數據無效
if (propertyCount <= 0 || datas.Length < propertyCount)
return null;
//記錄數據名稱及類型
for (int i = 0; i < propertyCount; i++)
{
propertyNameTypes[i] = new KeyValuePair<string, string>(propertyNameTypes[i].Key, datas[i]);
}
}
curRowIndex++;
}
if (propertyNameTypes.Length == 0 || allItemValueRowList.Count == 0)
return null;
ExcelMediumData excelMediumData = new ExcelMediumData();
//類名
excelMediumData.excelName = excelReader.Name;
//Dictionary<數據名稱,數據類型>
excelMediumData.propertyNameTypeDic = new Dictionary<string, string>();
//轉換存儲格式
for (int i = 0; i < propertyCount; i++)
{
//數據名重複,數據無效
if (excelMediumData.propertyNameTypeDic.ContainsKey(propertyNameTypes[i].Key))
return null;
excelMediumData.propertyNameTypeDic.Add(propertyNameTypes[i].Key, propertyNameTypes[i].Value);
}
excelMediumData.allItemValueRowList = allItemValueRowList;
return excelMediumData;
}
//寫文件
private static bool WriteCodeStrToSave(string writeFilePath, string codeFileName, string classCodeStr)
{
if (string.IsNullOrEmpty(codeFileName) || string.IsNullOrEmpty(classCodeStr))
return false;
//檢查導出路徑
if (!Directory.Exists(writeFilePath))
Directory.CreateDirectory(writeFilePath);
//寫文件,生成CS類文件
StreamWriter sw = new StreamWriter(writeFilePath + "/" + codeFileName + ".cs");
sw.WriteLine(classCodeStr);
sw.Close();
//
UnityEditor.AssetDatabase.Refresh();
return true;
}
#endregion
}
#endif
3. 自動生成C#類和Asset文件
#if UNITY_EDITOR
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Text;
public class ExcelCodeCreater
{
#region --- Create Code ---
//創建代碼,生成數據C#類
public static string CreateCodeStrByExcelData(ExcelMediumData excelMediumData)
{
if (excelMediumData == null)
return null;
//Excel名字
string excelName = excelMediumData.excelName;
if (string.IsNullOrEmpty(excelName))
return null;
//Dictionary<字段名稱, 字段類型>
Dictionary<string, string> propertyNameTypeDic = excelMediumData.propertyNameTypeDic;
if (propertyNameTypeDic == null || propertyNameTypeDic.Count == 0)
return null;
//List<一行數據>,List<Dictionary<字段名稱, 一行的每個單元格字段值>>
List<Dictionary<string, string>> allItemValueRowList = excelMediumData.allItemValueRowList;
if (allItemValueRowList == null || allItemValueRowList.Count == 0)
return null;
//行數據類名
string itemClassName = excelName + "ExcelItem";
//整體數據類名
string dataClassName = excelName + "ExcelData";
//生成類
StringBuilder classSource = new StringBuilder();
classSource.Append("/*Auto Create, Don't Edit !!!*/\n");
classSource.Append("\n");
//添加引用
classSource.Append("using UnityEngine;\n");
classSource.Append("using System.Collections.Generic;\n");
classSource.Append("using System;\n");
classSource.Append("using System.IO;\n");
classSource.Append("\n");
//生成行數據類,記錄每行數據
classSource.Append(CreateExcelRowItemClass(itemClassName, propertyNameTypeDic));
classSource.Append("\n");
//生成整體數據類,記錄整個Excel的所有行數據
classSource.Append(CreateExcelDataClass(dataClassName, itemClassName));
classSource.Append("\n");
//生成Asset操作類,用於自動創建Excel對應的Asset文件並賦值
classSource.Append(CreateExcelAssetClass(excelMediumData));
classSource.Append("\n");
return classSource.ToString();
}
//----------
//生成行數據類
private static StringBuilder CreateExcelRowItemClass(string itemClassName, Dictionary<string, string> propertyNameTypeDic)
{
//生成Excel行數據類
StringBuilder classSource = new StringBuilder();
classSource.Append("[Serializable]\n");
classSource.Append("public class " + itemClassName + "\n");
classSource.Append("{\n");
//聲明所有字段
foreach (var item in propertyNameTypeDic)
{
classSource.Append(CreateCodeProperty(item.Key, item.Value));
}
classSource.Append("}\n");
return classSource;
}
//聲明行數據類字段
private static string CreateCodeProperty(string name, string type)
{
if (string.IsNullOrEmpty(name))
return null;
//判斷字段類型
if (type == "int" || type == "Int" || type == "INT")
type = "int";
else if (type == "float" || type == "Float" || type == "FLOAT")
type = "float";
else if (type == "bool" || type == "Bool" || type == "BOOL")
type = "bool";
else
type = "string";
//聲明
string propertyStr = "\tpublic " + type + " " + name + ";\n";
return propertyStr;
}
//----------
//生成數據類
private static StringBuilder CreateExcelDataClass(string dataClassName, string itemClassName)
{
StringBuilder classSource = new StringBuilder();
classSource.Append("[CreateAssetMenu(fileName = \"" + dataClassName + "\", menuName = \"Excel To ScriptableObject/Create " + dataClassName + "\", order = 1)]\n");
classSource.Append("public class " + dataClassName + " : ExcelDataBase\n");
classSource.Append("{\n");
//聲明字段,行數據類數組
classSource.Append("\tpublic " + itemClassName + "[] items;\n");
classSource.Append("}\n");
return classSource;
}
//----------
//生成Asset操作類
private static StringBuilder CreateExcelAssetClass(ExcelMediumData excelMediumData)
{
if (excelMediumData == null)
return null;
string excelName = excelMediumData.excelName;
if (string.IsNullOrEmpty(excelName))
return null;
Dictionary<string, string> propertyNameTypeDic = excelMediumData.propertyNameTypeDic;
if (propertyNameTypeDic == null || propertyNameTypeDic.Count == 0)
return null;
List<Dictionary<string, string>> allItemValueRowList = excelMediumData.allItemValueRowList;
if (allItemValueRowList == null || allItemValueRowList.Count == 0)
return null;
string itemClassName = excelName + "ExcelItem";
string dataClassName = excelName + "ExcelData";
StringBuilder classSource = new StringBuilder();
classSource.Append("#if UNITY_EDITOR\n");
//類名
classSource.Append("public class " + excelName + "AssetAssignment\n");
classSource.Append("{\n");
//方法名
classSource.Append("\tpublic static bool CreateAsset(List<Dictionary<string, string>> allItemValueRowList, string excelAssetPath)\n");
//方法體,若有需要可加入try/catch
classSource.Append("\t{\n");
classSource.Append("\t\tif (allItemValueRowList == null || allItemValueRowList.Count == 0)\n");
classSource.Append("\t\t\treturn false;\n");
classSource.Append("\t\tint rowCount = allItemValueRowList.Count;\n");
classSource.Append("\t\t" + itemClassName + "[] items = new " + itemClassName + "[rowCount];\n");
classSource.Append("\t\tfor (int i = 0; i < items.Length; i++)\n");
classSource.Append("\t\t{\n");
classSource.Append("\t\t\titems[i] = new " + itemClassName + "();\n");
foreach (var item in propertyNameTypeDic)
{
classSource.Append("\t\t\titems[i]." + item.Key + " = ");
classSource.Append(AssignmentCodeProperty("allItemValueRowList[i][\"" + item.Key + "\"]", propertyNameTypeDic[item.Key]));
classSource.Append(";\n");
}
classSource.Append("\t\t}\n");
classSource.Append("\t\t" + dataClassName + " excelDataAsset = ScriptableObject.CreateInstance<" + dataClassName + ">();\n");
classSource.Append("\t\texcelDataAsset.items = items;\n");
classSource.Append("\t\tif (!Directory.Exists(excelAssetPath))\n");
classSource.Append("\t\t\tDirectory.CreateDirectory(excelAssetPath);\n");
classSource.Append("\t\tstring pullPath = excelAssetPath + \"/\" + typeof(" + dataClassName + ").Name + \".asset\";\n");
classSource.Append("\t\tUnityEditor.AssetDatabase.DeleteAsset(pullPath);\n");
classSource.Append("\t\tUnityEditor.AssetDatabase.CreateAsset(excelDataAsset, pullPath);\n");
classSource.Append("\t\tUnityEditor.AssetDatabase.Refresh();\n");
classSource.Append("\t\treturn true;\n");
classSource.Append("\t}\n");
//
classSource.Append("}\n");
classSource.Append("#endif\n");
return classSource;
}
//聲明Asset操作類字段
private static string AssignmentCodeProperty(string stringValue, string type)
{
//判斷類型
if (type == "int" || type == "Int" || type == "INT")
{
return "Convert.ToInt32(" + stringValue + ")";
}
else if (type == "float" || type == "Float" || type == "FLOAT")
{
return "Convert.ToSingle(" + stringValue + ")";
}
else if (type == "bool" || type == "Bool" || type == "BOOL")
{
return "Convert.ToBoolean(" + stringValue + ")";
}
else
return stringValue;
}
#endregion
}
#endif
4. 編寫操作面板窗口
#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;
using System.IO;
using System.Collections.Generic;
using System.Linq;
public class BuildExcelEditor : Editor
{
}
public class BuildExcelWindow : EditorWindow
{
//[MenuItem("MyTools/Excel/Build Script")]
//public static void CreateExcelCode()
//{
// ExcelDataReader.ReadAllExcelToCode();
//}
//[MenuItem("MyTools/Excel/Build Asset")]
//public static void CreateExcelAssset()
//{
// ExcelDataReader.CreateAllExcelAsset();
//}
[MenuItem("MyTools/Excel/Build Window")]
public static void ShowExcelWindow()
{
//顯示操作窗口方式一
//BuildExcelWindow buildExcelWindow = GetWindow<BuildExcelWindow>();
//buildExcelWindow.Show();
//顯示操作窗口方式二
EditorWindow.GetWindow(typeof(BuildExcelWindow));
}
private string showNotify;
private Vector2 scrollPosition = Vector2.zero;
private List<string> fileNameList = new List<string>();
private List<string> filePathList = new List<string>();
private void Awake()
{
titleContent.text = "Excel數據讀取";
}
private void OnEnable()
{
showNotify = "";
GetExcelFile();
}
private void OnDisable()
{
showNotify = "";
fileNameList.Clear();
filePathList.Clear();
}
private void OnGUI()
{
scrollPosition = GUILayout.BeginScrollView(scrollPosition,
GUILayout.Width(position.width), GUILayout.Height(position.height));
//自動創建C#腳本
GUILayout.Space(10);
GUILayout.Label("Excel To Script");
for (int i = 0; i < fileNameList.Count; i++)
{
if (GUILayout.Button(fileNameList[i], GUILayout.Width(200), GUILayout.Height(30)))
{
SelectExcelToCodeByIndex(i);
}
}
if (GUILayout.Button("All Excel", GUILayout.Width(200), GUILayout.Height(30)))
{
SelectExcelToCodeByIndex(-1);
}
//自動創建Asset文件
GUILayout.Space(20);
GUILayout.Label("Script To Asset");
for (int i = 0; i < fileNameList.Count; i++)
{
if (GUILayout.Button(fileNameList[i], GUILayout.Width(200), GUILayout.Height(30)))
{
SelectCodeToAssetByIndex(i);
}
}
if (GUILayout.Button("All Excel", GUILayout.Width(200), GUILayout.Height(30)))
{
SelectCodeToAssetByIndex(-1);
}
//
GUILayout.Space(20);
GUILayout.Label(showNotify);
//
GUILayout.EndScrollView();
//this.Repaint();
}
//讀取指定路徑下的Excel文件名
private void GetExcelFile()
{
fileNameList.Clear();
filePathList.Clear();
string[] excelFileFullPaths = Directory.GetFiles(ExcelDataReader.excelFilePath, "*.xlsx");
if (excelFileFullPaths == null || excelFileFullPaths.Length == 0)
{
showNotify = ExcelDataReader.excelFilePath + "路徑下沒有找到Excel文件";
return;
}
filePathList.AddRange(excelFileFullPaths);
for (int i = 0; i < filePathList.Count; i++)
{
string fileName = filePathList[i].Split('/').LastOrDefault();
fileName = filePathList[i].Split('\\').LastOrDefault();
fileNameList.Add(fileName);
}
showNotify = "找到Excel文件:" + fileNameList.Count + "個";
}
//自動創建C#腳本
private void SelectExcelToCodeByIndex(int index)
{
if (index >= 0 && index < filePathList.Count)
{
string fullPath = filePathList[index];
ExcelDataReader.ReadOneExcelToCode(fullPath);
}
else
{
ExcelDataReader.ReadAllExcelToCode();
}
}
//自動創建Asset文件
private void SelectCodeToAssetByIndex(int index)
{
if (index >= 0 && index < filePathList.Count)
{
string fullPath = filePathList[index];
ExcelDataReader.CreateOneExcelAsset(fullPath);
}
else
{
ExcelDataReader.CreateAllExcelAsset();
}
}
}
#endif
5. 操作成功,遊戲內使用數據
表格數據類基類
public class ExcelDataBase : ScriptableObject
{
}
自動創建的C#類:
/*Auto Create, Don't Edit !!!*/
using UnityEngine;
using System.Collections.Generic;
using System;
using System.IO;
[Serializable]
public class RoleParameExcelItem
{
public string id;
public int attack;
public int health;
public float speed;
public bool isFly;
}
[CreateAssetMenu(fileName = "RoleParameExcelData", menuName = "Excel To ScriptableObject/Create RoleParameExcelData", order = 1)]
public class RoleParameExcelData : ExcelDataBase
{
public RoleParameExcelItem[] items;
}
#if UNITY_EDITOR
public class RoleParameAssetAssignment
{
public static bool CreateAsset(List<Dictionary<string, string>> allItemValueRowList, string excelAssetPath)
{
if (allItemValueRowList == null || allItemValueRowList.Count == 0)
return false;
int rowCount = allItemValueRowList.Count;
RoleParameExcelItem[] items = new RoleParameExcelItem[rowCount];
for (int i = 0; i < items.Length; i++)
{
items[i] = new RoleParameExcelItem();
items[i].id = allItemValueRowList[i]["id"];
items[i].attack = Convert.ToInt32(allItemValueRowList[i]["attack"]);
items[i].health = Convert.ToInt32(allItemValueRowList[i]["health"]);
items[i].speed = Convert.ToSingle(allItemValueRowList[i]["speed"]);
items[i].isFly = Convert.ToBoolean(allItemValueRowList[i]["isFly"]);
}
RoleParameExcelData excelDataAsset = ScriptableObject.CreateInstance<RoleParameExcelData>();
excelDataAsset.items = items;
if (!Directory.Exists(excelAssetPath))
Directory.CreateDirectory(excelAssetPath);
string pullPath = excelAssetPath + "/" + typeof(RoleParameExcelData).Name + ".asset";
UnityEditor.AssetDatabase.DeleteAsset(pullPath);
UnityEditor.AssetDatabase.CreateAsset(excelDataAsset, pullPath);
UnityEditor.AssetDatabase.Refresh();
return true;
}
}
#endif
自動創建的ScriptableObject對應Asset文件
測試遊戲內使用
public class ExcelTest : MonoBehaviour
{
void Start()
{
RoleParameExcelData roleParameExcelData = Resources.Load<RoleParameExcelData>("ExcelAsset/RoleParameExcelData");
if(roleParameExcelData != null)
{
for (int i = 0; i < roleParameExcelData.items.Length; i++)
{
Debug.Log(roleParameExcelData.items[i].id);
}
}
}
}