当前位置:   article > 正文

Unity读取Excel导出Json,游戏中加载Json生成List<T>配置_unityjson转 list

unityjson转 list

读取Excel导出Json和对应数据格式Class

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEditor;
  5. using System.IO;
  6. using Excel;
  7. using System.Data;
  8. using System;
  9. using System.Linq;
  10. public class ExcelToJson : Editor
  11. {
  12. //[MenuItem("TGDTools/ExcelToJson")]
  13. public static void ReadExcelToJson()
  14. {
  15. //目标文件夹
  16. string sourceDir = string.Format("{0}/../../excelsconfig", Environment.CurrentDirectory);
  17. if(!Directory.Exists(sourceDir))
  18. {
  19. Debug.LogError(string.Format("目标文件夹不存在!:{0}", sourceDir));
  20. return;
  21. }
  22. //检查文件
  23. string sourceFile = string.Format("{0}/测试表.xlsx", sourceDir);
  24. if (!File.Exists(sourceFile))
  25. {
  26. Debug.LogError(string.Format("目标文件不存在!:{0}", sourceFile));
  27. return;
  28. }
  29. //读取源文件
  30. Dictionary<string, Dictionary<string, object>> holder = new Dictionary<string, Dictionary<string, object>>();
  31. if (!ReadExcel(sourceFile, holder))
  32. {
  33. Debug.LogError(string.Format("读取目标文件失败 : {0}", sourceFile));
  34. return;
  35. }
  36. //检查生成目录
  37. string targetDir = string.Format("{0}/Assets/Resources/ExcelToJson", Environment.CurrentDirectory);
  38. if (!Directory.Exists(targetDir))
  39. {
  40. Directory.CreateDirectory(targetDir);
  41. Debug.LogFormat("目标文件夹不存在,创建新目录 : {0}", targetDir);
  42. }
  43. //转换格式并保存
  44. string tablePath = string.Format("{0}/TextExcelToJson.json", targetDir);
  45. if (File.Exists(tablePath))
  46. {
  47. File.Delete(tablePath);
  48. }
  49. FileInfo fileInfo = new FileInfo(tablePath);
  50. using (StreamWriter streamWriter = fileInfo.CreateText())
  51. {
  52. streamWriter.Write(LitJson.JsonMapper.ToJson(holder));
  53. streamWriter.Flush();
  54. streamWriter.Close();
  55. }
  56. AssetDatabase.Refresh();
  57. Debug.Log("=================== 生成成功!!!");
  58. }
  59. private static bool ReadExcel(string filePath, Dictionary<string, Dictionary<string, object>> dataHolder)
  60. {
  61. try
  62. {
  63. EditorUtility.DisplayProgressBar("ReadExcel", filePath, 0);
  64. //读取文件
  65. using (FileStream fileStream = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
  66. {
  67. //创建读取
  68. IExcelDataReader dataReader = ExcelReaderFactory.CreateOpenXmlReader(fileStream);
  69. //转换格式
  70. DataSet dataSet = dataReader.AsDataSet();
  71. int index = 0;
  72. //遍历页签
  73. foreach (DataTable dataTable in dataSet.Tables)
  74. {
  75. //页签名称
  76. string sheetName = dataTable.TableName;
  77. //Debug.LogFormat("------------->> sheetName:{0}", sheetName);
  78. EditorUtility.DisplayProgressBar("Read Excel Sheet", sheetName, index*1f/ dataSet.Tables.Count);
  79. index++;
  80. //一个页签
  81. if (!dataHolder.TryGetValue(sheetName, out Dictionary<string, object> sheetData))
  82. {
  83. sheetData = new Dictionary<string, object>();
  84. dataHolder.Add(sheetName, sheetData);
  85. }
  86. //读取行
  87. DataRowCollection dataRows = dataTable.Rows;
  88. //读取列
  89. DataColumnCollection dataColumns = dataTable.Columns;
  90. //Debug.LogFormat("------------->> dataRows.Count:{0} dataColumns.Count:{1}", dataRows.Count, dataColumns.Count);
  91. //遍历
  92. for (int i = 1; i < dataColumns.Count; i++)
  93. {
  94. string name = dataRows[0][i].ToString().Trim();
  95. if (!string.IsNullOrEmpty(name))
  96. {
  97. //Debug.LogFormat("------------->> i:{0} name:{1}", i, name);
  98. for (int j = 1; j < dataRows.Count; j++)
  99. {
  100. string key = dataRows[j][0].ToString().Trim();
  101. //Debug.LogFormat("------------->> j:{0} key:{1}", j, key);
  102. //一行数据
  103. string value = dataRows[j][i].ToString().Trim();
  104. if (!string.IsNullOrEmpty(value))
  105. {
  106. //Debug.LogFormat("------------->> i:{0} j:{1} value:{2}", i, j, value);
  107. //dataHolder.Add(name, value);
  108. if (!sheetData.TryGetValue(key, out object data))
  109. {
  110. data = new Dictionary<string, string>();
  111. sheetData.Add(key, data);
  112. }
  113. (data as Dictionary<string, string>).Add(name, value);
  114. }
  115. }
  116. }
  117. }
  118. }
  119. }
  120. EditorUtility.ClearProgressBar();
  121. return true;
  122. }
  123. catch (Exception e)
  124. {
  125. Debug.LogError(string.Format("读取数据异常 : {0}", e.Message));
  126. }
  127. return false;
  128. }
  129. [MenuItem("TGDTools/ExportExcel")]
  130. public static void ExportExcel()
  131. {
  132. //目标文件夹
  133. string sourceDir = string.Format("{0}/../../excelsconfig", Environment.CurrentDirectory);
  134. if (!Directory.Exists(sourceDir))
  135. {
  136. Debug.LogError(string.Format("目标文件夹不存在!:{0}", sourceDir));
  137. return;
  138. }
  139. List<string> fileList = RecursivePathGetFiles(sourceDir);
  140. for(int i=0; i<fileList.Count; i++)
  141. {
  142. string fileName = fileList[i];
  143. EditorUtility.DisplayProgressBar("ReadExcel", fileName, i*1f/fileList.Count);
  144. //检查文件
  145. if (!File.Exists(fileName))
  146. {
  147. Debug.LogError(string.Format("目标文件不存在!:{0}", fileName));
  148. continue;
  149. }
  150. ReadExcel(fileName);
  151. }
  152. EditorUtility.ClearProgressBar();
  153. AssetDatabase.Refresh();
  154. Debug.Log("=================== 生成成功!!!");
  155. }
  156. private static void ReadExcel(string fileName)
  157. {
  158. try
  159. {
  160. Debug.LogFormat("------------->>ReadExcel {0}", fileName);
  161. //读取文件
  162. using (FileStream fileStream = File.Open(fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
  163. {
  164. //创建读取
  165. IExcelDataReader dataReader = ExcelReaderFactory.CreateOpenXmlReader(fileStream);
  166. //转换格式
  167. DataSet dataSet = dataReader.AsDataSet();
  168. //读取表(第一个页签)
  169. DataTable dataTable = dataSet.Tables[0];
  170. CreateClasssFile(dataTable);
  171. CreateJsonFile(dataTable);
  172. }
  173. }
  174. catch (Exception e)
  175. {
  176. Debug.LogError(string.Format("读取数据异常 : {0}", e.Message));
  177. }
  178. }
  179. private static void CreateClasssFile(DataTable dataTable)
  180. {
  181. //页签名称
  182. string sheetName = dataTable.TableName;
  183. //读取行
  184. DataRowCollection dataRows = dataTable.Rows;
  185. //读取列
  186. DataColumnCollection dataColumns = dataTable.Columns;
  187. string text = "using System;\nusing System.Collections.Generic;\nnamespace TGDFramework.Core\n{\n public class " + sheetName + ("\n {\n");
  188. for (int i=0; i<dataColumns.Count; i++)
  189. {
  190. string valeName = dataRows[1][i].ToString().Trim();
  191. string valeType = dataRows[2][i].ToString().Trim();
  192. if (!string.IsNullOrEmpty(valeName) && !string.IsNullOrEmpty(valeType))
  193. {
  194. string memberStr = string.Format(" public {0} {1};\n", valeType, valeName);
  195. Debug.LogFormat("----------------CreateClasssFile------------->>> {0} {1}", valeType, valeName);
  196. text = String.Concat(text, memberStr);
  197. }
  198. }
  199. string tail = " }\n}\n";
  200. text = String.Concat(text, tail);
  201. string dir = string.Format("{0}/Assets/Scripts/TGDFramework/ExcelToJson/Table", Environment.CurrentDirectory);
  202. if (!Directory.Exists(dir))
  203. {
  204. Directory.CreateDirectory(dir);
  205. }
  206. string filePath = string.Format("{0}/{1}.cs", dir, sheetName);
  207. if (File.Exists(filePath))
  208. {
  209. File.Delete(filePath);
  210. }
  211. FileInfo fileInfo = new FileInfo(filePath);
  212. using (StreamWriter streamWriter = fileInfo.CreateText())
  213. {
  214. streamWriter.Write(text);
  215. streamWriter.Flush();
  216. streamWriter.Close();
  217. }
  218. Debug.LogFormat("----------------------------->>>create Class {0} succ!", sheetName);
  219. }
  220. private static void CreateJsonFile(DataTable dataTable)
  221. {
  222. //页签名称
  223. string sheetName = dataTable.TableName;
  224. //读取行
  225. DataRowCollection dataRows = dataTable.Rows;
  226. //读取列
  227. DataColumnCollection dataColumns = dataTable.Columns;
  228. List<object> dataHolder = new List<object>();
  229. //遍历
  230. for (int i = 3; i < dataRows.Count; i++)
  231. {
  232. string keyStr = dataRows[i][0].ToString().Trim();
  233. if (string.IsNullOrEmpty(keyStr))
  234. {
  235. break;
  236. }
  237. int key = int.Parse(keyStr);
  238. //Debug.LogFormat("----------------------------->>> key {0}", key);
  239. Dictionary<object, object> data = new Dictionary<object, object>();
  240. for (int j = 0; j < dataColumns.Count; j++)
  241. {
  242. string valeName = dataRows[1][j].ToString().Trim();
  243. string valeType = dataRows[2][j].ToString().Trim();
  244. string value = dataRows[i][j].ToString().Trim();
  245. //Debug.LogFormat("----------------------------->>> valeType:{0} valeName:{1} value:{2}", valeType, valeName, value);
  246. if (!string.IsNullOrEmpty(value))
  247. {
  248. if (valeType.Equals("int"))
  249. {
  250. data.Add(valeName, int.Parse(value));
  251. }
  252. else if (valeType.Equals("string"))
  253. {
  254. data.Add(valeName, value);
  255. }
  256. else if (valeType.Equals("List<int>"))
  257. {
  258. List<int> list = new List<int>();
  259. string[] listStr = value.Split('+');
  260. foreach(string str in listStr)
  261. {
  262. list.Add(int.Parse(str));
  263. }
  264. data.Add(valeName, list);
  265. }
  266. else if (valeType.Equals("List<string>"))
  267. {
  268. string[] listStr = value.Split('+');
  269. List<string> list = new List<string>(listStr);
  270. data.Add(valeName, list);
  271. }
  272. else if (valeType.Equals("Dictionary<string,string>"))
  273. {
  274. string[] listStr = value.Split('|');
  275. Dictionary<string, string> dic = listStr.ToDictionary(
  276. sKey => { /*Debug.Log(sKey);*/ return sKey.Split('+')[0]; },
  277. sElement => { /*Debug.Log(sElement);*/return sElement.Split('+')[1]; }
  278. );
  279. data.Add(valeName, dic);
  280. }
  281. }
  282. }
  283. dataHolder.Add(data);
  284. }
  285. string dir = string.Format("{0}/Assets/Scripts/TGDFramework/ExcelToJson/Json", Environment.CurrentDirectory);
  286. if (!Directory.Exists(dir))
  287. {
  288. Directory.CreateDirectory(dir);
  289. }
  290. string filePath = string.Format("{0}/{1}.json", dir, sheetName);
  291. if (File.Exists(filePath))
  292. {
  293. File.Delete(filePath);
  294. }
  295. FileInfo fileInfo = new FileInfo(filePath);
  296. using (StreamWriter streamWriter = fileInfo.CreateText())
  297. {
  298. streamWriter.Write(LitJson.JsonMapper.ToJson(dataHolder));
  299. streamWriter.Flush();
  300. streamWriter.Close();
  301. }
  302. Debug.LogFormat("----------------------------->>>create Json {0} succ!", sheetName);
  303. }
  304. public static List<string> RecursivePathGetFiles(string path)
  305. {
  306. List<string> fileList = new List<string>();
  307. fileList.Clear();
  308. RecursivePath(path, fileList);
  309. return fileList;
  310. }
  311. private static void RecursivePath(string path, List<string> fileList)
  312. {
  313. string[] files = Directory.GetFiles(path);
  314. string[] dirs = Directory.GetDirectories(path);
  315. int count = files.Length;
  316. for (int i = 0; i < count; i++)
  317. {
  318. string ext = Path.GetExtension(files[i]);
  319. if (ext.Equals(".mat"))
  320. {
  321. continue;
  322. }
  323. fileList.Add(files[i].Replace("\\", "/"));
  324. }
  325. count = dirs.Length;
  326. for (int i = 0; i < count; i++)
  327. {
  328. RecursivePath(dirs[i], fileList);
  329. }
  330. }
  331. }

游戏中读取Json,生成List<T>配置

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using TGDFramework.Core;
  5. using LitJson;
  6. using System.IO;
  7. using System.Linq;
  8. namespace TGDFramework.Core
  9. {
  10. public class LoadJsonData : Singleton<LoadJsonData>
  11. {
  12. private Dictionary<string, object> m_TextExcelJson;
  13. public Dictionary<string, object> TextExcelJson
  14. {
  15. get
  16. {
  17. if (m_TextExcelJson == null)
  18. {
  19. TextAsset textAsset = Resources.Load<TextAsset>("ExcelToJson/TextExcelToJson");
  20. if (textAsset != null)
  21. {
  22. m_TextExcelJson = JsonMapper.ToObject<Dictionary<string, object>>(textAsset.text);
  23. }
  24. }
  25. return m_TextExcelJson;
  26. }
  27. }
  28. private TableData<PTextSheet> mPTextSheetTable;
  29. public void Init()
  30. {
  31. Debug.Log(TextExcelJson.ToString());
  32. //LoadJson<P>("TextExcelToJson");
  33. string dir = string.Format("Assets/Scripts/TGDFramework/ExcelToJson/Json/");
  34. mPTextSheetTable = TableData<PTextSheet>.Instance;
  35. mPTextSheetTable.LoadData("PTextSheet", dir);
  36. PTextSheet data = Instance.GetPExhibitionData().Where(p => p.id == 3).First();
  37. PTextSheet data1 = mPTextSheetTable.GetDataByKey(4);
  38. Debug.LogFormat("============>>> id:{0} name:{1} {2} ", data.id, data.name, data.TestList_int.ToString(), data.TestList_string.ToString());
  39. foreach(string str in data1.TestList_string)
  40. {
  41. Debug.LogFormat("============>>> str:{0}", str);
  42. }
  43. foreach (var item in data1.TestDic_stringString)
  44. {
  45. Debug.LogFormat("============>>> key:{0} value:{1}", item.Key, item.Value);
  46. }
  47. foreach (var item in data1.TestDic_intintTGD)
  48. {
  49. Debug.LogFormat("============>>> key:{0} value:{1}", item.Key, item.Value);
  50. }
  51. }
  52. private void LoadJson<T>(string fileName)
  53. {
  54. string filePath = string.Format("ExcelToJson/{0}", fileName);
  55. if (!File.Exists(filePath))
  56. {
  57. return;
  58. }
  59. TextAsset tableAsset = Resources.Load<TextAsset>(filePath);
  60. if (tableAsset == null)
  61. {
  62. return;
  63. }
  64. }
  65. public List<PTextSheet> GetPExhibitionData()
  66. {
  67. return mPTextSheetTable.GetDataList();
  68. }
  69. //public static string GetTableTranslateString<T>(T tableData, string keyName) where T : class
  70. //{
  71. // string fullClassName = tableData.GetType().ToString();
  72. // string[] listName = fullClassName.Split('.');
  73. // string className = listName[listName.Length - 1];
  74. // if (Instance.TextExcelJson.ContainsKey(className))
  75. // {
  76. // Dictionary<string, Dictionary<string, string>> dataRow = Instance.TextExcelJson[className];
  77. // string id = typeof(T).GetField("id").GetValue(tableData).ToString();
  78. // if (dataRow.ContainsKey(id))
  79. // {
  80. // Dictionary<string, string> data = dataRow[id];
  81. // string strKey = string.Format("{0}_CN", keyName);
  82. // if (data.ContainsKey(strKey))
  83. // {
  84. // string text = data[strKey];
  85. // //Debug.LogFormat("------------------------>>>> text {0} ", text);
  86. // return text;
  87. // }
  88. // }
  89. // }
  90. // return null;
  91. //}
  92. }
  93. }
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. using LitJson;
  6. using System.IO;
  7. namespace TGDFramework.Core
  8. {
  9. public sealed class TableData<T> : Singleton<TableData<T>>
  10. {
  11. private List<T> mTableDataList;
  12. private Dictionary<int, T> mTableDataDict;
  13. public TableData()
  14. {
  15. mTableDataDict = new Dictionary<int, T>();
  16. }
  17. public void LoadData(string tableName)
  18. {
  19. string abVersion = "";
  20. var assetName = tableName + ".json";
  21. string tablePath = string.IsNullOrEmpty(abVersion) ? Const.CONFIG_DATA_PATH : Const.CONFIG_DATA_PATH + "-" + abVersion;
  22. TextAsset tableAsset = (TextAsset)BundleManager.Instance.LoadBundle(tablePath, assetName);
  23. #if UNITY_EDITOR
  24. Debug.Log("load tableName: " + tableName);
  25. #endif
  26. mTableDataList = JsonMapper.ToObject<List<T>>(tableAsset.text);
  27. for (int i = 0; i < mTableDataList.Count; i++)
  28. {
  29. T item = mTableDataList[i];
  30. int primaryKey = int.Parse(typeof(T).GetField("id").GetValue(item).ToString());
  31. mTableDataDict[primaryKey] = item;
  32. }
  33. }
  34. public void LoadData(string tableName, string dir)
  35. {
  36. string path = dir + tableName +".json";
  37. TextAsset asset = (TextAsset)UnityEditor.AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(path);
  38. #if UNITY_EDITOR
  39. Debug.Log("load tableName: " + path);
  40. #endif
  41. mTableDataList = JsonMapper.ToObject<List<T>>(asset.text);
  42. for (int i = 0; i < mTableDataList.Count; i++)
  43. {
  44. T item = mTableDataList[i];
  45. int primaryKey = int.Parse(typeof(T).GetField("id").GetValue(item).ToString());
  46. mTableDataDict[primaryKey] = item;
  47. }
  48. }
  49. public List<T> GetDataList()
  50. {
  51. return this.mTableDataList;
  52. }
  53. public T GetDataByKey(int id)
  54. {
  55. T data = default(T);
  56. this.mTableDataDict.TryGetValue(id, out data);
  57. return data;
  58. }
  59. }
  60. }

https://download.csdn.net/download/u012366310/20419625

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/794124
推荐阅读
相关标签
  

闽ICP备14008679号