ExcelExporter.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using Microsoft.CodeAnalysis;
  9. using Microsoft.CodeAnalysis.CSharp;
  10. using Microsoft.CodeAnalysis.Emit;
  11. using MongoDB.Bson;
  12. using MongoDB.Bson.Serialization;
  13. using MongoDB.Bson.Serialization.Attributes;
  14. using OfficeOpenXml;
  15. using LicenseContext = OfficeOpenXml.LicenseContext;
  16. namespace ET
  17. {
  18. public enum ConfigType
  19. {
  20. c = 0,
  21. s = 1,
  22. cs = 2,
  23. }
  24. class HeadInfo
  25. {
  26. [BsonElement]
  27. public string FieldCS;
  28. public string FieldDesc;
  29. public string FieldName;
  30. public string FieldType;
  31. public int FieldIndex;
  32. public HeadInfo(string cs, string desc, string name, string type, int index)
  33. {
  34. this.FieldCS = cs;
  35. this.FieldDesc = desc;
  36. this.FieldName = name;
  37. this.FieldType = type;
  38. this.FieldIndex = index;
  39. }
  40. }
  41. // 这里加个标签是为了防止编译时裁剪掉protobuf,因为整个tool工程没有用到protobuf,编译会去掉引用,然后动态编译就会出错
  42. class Table
  43. {
  44. public bool C;
  45. public bool S;
  46. public int Index;
  47. public Dictionary<string, HeadInfo> HeadInfos = new Dictionary<string, HeadInfo>();
  48. }
  49. public static class ExcelExporter
  50. {
  51. private static string template;
  52. private const string ClientClassDir = "../Unity/Assets/Scripts/Codes/Model/Generate/Client/Config";
  53. // 服务端因为机器人的存在必须包含客户端所有配置,所以单独的c字段没有意义,单独的c就表示cs
  54. private const string ServerClassDir = "../Unity/Assets/Scripts/Codes/Model/Generate/Server/Config";
  55. private const string CSClassDir = "../Unity/Assets/Scripts/Codes/Model/Generate/ClientServer/Config";
  56. private const string excelDir = "../Unity/Assets/Config/Excel/";
  57. private const string jsonDir = "../Config/Json/{0}/{1}";
  58. private const string clientProtoDir = "../Unity/Assets/Bundles/Config";
  59. private const string serverProtoDir = "../Config/Excel/{0}/{1}";
  60. private const string replaceStr = "/{0}/{1}";
  61. private static Assembly[] configAssemblies = new Assembly[3];
  62. private static Dictionary<string, Table> tables = new Dictionary<string, Table>();
  63. private static Dictionary<string, ExcelPackage> packages = new Dictionary<string, ExcelPackage>();
  64. private static Table GetTable(string protoName)
  65. {
  66. if (!tables.TryGetValue(protoName, out var table))
  67. {
  68. table = new Table();
  69. tables[protoName] = table;
  70. }
  71. return table;
  72. }
  73. public static ExcelPackage GetPackage(string filePath)
  74. {
  75. if (!packages.TryGetValue(filePath, out var package))
  76. {
  77. using Stream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
  78. package = new ExcelPackage(stream);
  79. packages[filePath] = package;
  80. }
  81. return package;
  82. }
  83. public static void Export()
  84. {
  85. try
  86. {
  87. template = File.ReadAllText("Template.txt");
  88. ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
  89. if (Directory.Exists(ClientClassDir))
  90. {
  91. Directory.Delete(ClientClassDir, true);
  92. }
  93. if (Directory.Exists(ServerClassDir))
  94. {
  95. Directory.Delete(ServerClassDir, true);
  96. }
  97. if (Directory.Exists(CSClassDir))
  98. {
  99. Directory.Delete(CSClassDir, true);
  100. }
  101. string jsonProtoDirParent = jsonDir.Replace(replaceStr, string.Empty);
  102. if (Directory.Exists(jsonProtoDirParent))
  103. {
  104. Directory.Delete(jsonProtoDirParent, true);
  105. }
  106. string serverProtoDirParent = serverProtoDir.Replace(replaceStr, string.Empty);
  107. if (Directory.Exists(serverProtoDirParent))
  108. {
  109. Directory.Delete(serverProtoDirParent, true);
  110. }
  111. List<string> files = FileHelper.GetAllFiles(excelDir);
  112. foreach (string path in files)
  113. {
  114. string fileName = Path.GetFileName(path);
  115. if (!fileName.EndsWith(".xlsx") || fileName.StartsWith("~$") || fileName.Contains("#"))
  116. {
  117. continue;
  118. }
  119. string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileName);
  120. string fileNameWithoutCS = fileNameWithoutExtension;
  121. string cs = "cs";
  122. if (fileNameWithoutExtension.Contains("@"))
  123. {
  124. string[] ss = fileNameWithoutExtension.Split("@");
  125. fileNameWithoutCS = ss[0];
  126. cs = ss[1];
  127. }
  128. if (cs == "")
  129. {
  130. cs = "cs";
  131. }
  132. ExcelPackage p = GetPackage(Path.GetFullPath(path));
  133. string protoName = fileNameWithoutCS;
  134. if (fileNameWithoutCS.Contains('_'))
  135. {
  136. protoName = fileNameWithoutCS.Substring(0, fileNameWithoutCS.LastIndexOf('_'));
  137. }
  138. Table table = GetTable(protoName);
  139. if (cs.Contains("c"))
  140. {
  141. table.C = true;
  142. }
  143. if (cs.Contains("s"))
  144. {
  145. table.S = true;
  146. }
  147. ExportExcelClass(p, protoName, table);
  148. }
  149. foreach (var kv in tables)
  150. {
  151. if (kv.Value.C)
  152. {
  153. ExportClass(kv.Key, kv.Value.HeadInfos, ConfigType.c);
  154. }
  155. if (kv.Value.S)
  156. {
  157. ExportClass(kv.Key, kv.Value.HeadInfos, ConfigType.s);
  158. }
  159. ExportClass(kv.Key, kv.Value.HeadInfos, ConfigType.cs);
  160. }
  161. // 动态编译生成的配置代码
  162. configAssemblies[(int) ConfigType.c] = DynamicBuild(ConfigType.c);
  163. configAssemblies[(int) ConfigType.s] = DynamicBuild(ConfigType.s);
  164. configAssemblies[(int) ConfigType.cs] = DynamicBuild(ConfigType.cs);
  165. List<string> excels = FileHelper.GetAllFiles(excelDir, "*.xlsx");
  166. foreach (string path in excels)
  167. {
  168. ExportExcel(path);
  169. }
  170. if (Directory.Exists(clientProtoDir))
  171. {
  172. Directory.Delete(clientProtoDir, true);
  173. }
  174. FileHelper.CopyDirectory("../Config/Excel/c", clientProtoDir);
  175. Log.Console("Export Excel Sucess!");
  176. }
  177. catch (Exception e)
  178. {
  179. Log.Console(e.ToString());
  180. }
  181. finally
  182. {
  183. tables.Clear();
  184. foreach (var kv in packages)
  185. {
  186. kv.Value.Dispose();
  187. }
  188. packages.Clear();
  189. }
  190. }
  191. private static void ExportExcel(string path)
  192. {
  193. string dir = Path.GetDirectoryName(path);
  194. string relativePath = Path.GetRelativePath(excelDir, dir);
  195. string fileName = Path.GetFileName(path);
  196. if (!fileName.EndsWith(".xlsx") || fileName.StartsWith("~$") || fileName.Contains("#"))
  197. {
  198. return;
  199. }
  200. string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileName);
  201. string fileNameWithoutCS = fileNameWithoutExtension;
  202. string cs = "cs";
  203. if (fileNameWithoutExtension.Contains("@"))
  204. {
  205. string[] ss = fileNameWithoutExtension.Split("@");
  206. fileNameWithoutCS = ss[0];
  207. cs = ss[1];
  208. }
  209. if (cs == "")
  210. {
  211. cs = "cs";
  212. }
  213. string protoName = fileNameWithoutCS;
  214. if (fileNameWithoutCS.Contains('_'))
  215. {
  216. protoName = fileNameWithoutCS.Substring(0, fileNameWithoutCS.LastIndexOf('_'));
  217. }
  218. Table table = GetTable(protoName);
  219. ExcelPackage p = GetPackage(Path.GetFullPath(path));
  220. if (cs.Contains("c"))
  221. {
  222. ExportExcelJson(p, fileNameWithoutCS, table, ConfigType.c, relativePath);
  223. ExportExcelProtobuf(ConfigType.c, protoName, relativePath);
  224. }
  225. if (cs.Contains("s"))
  226. {
  227. ExportExcelJson(p, fileNameWithoutCS, table, ConfigType.s, relativePath);
  228. ExportExcelProtobuf(ConfigType.s, protoName, relativePath);
  229. }
  230. ExportExcelJson(p, fileNameWithoutCS, table, ConfigType.cs, relativePath);
  231. ExportExcelProtobuf(ConfigType.cs, protoName, relativePath);
  232. }
  233. private static string GetProtoDir(ConfigType configType, string relativeDir)
  234. {
  235. return string.Format(serverProtoDir, configType.ToString(), relativeDir);
  236. }
  237. private static Assembly GetAssembly(ConfigType configType)
  238. {
  239. return configAssemblies[(int) configType];
  240. }
  241. private static string GetClassDir(ConfigType configType)
  242. {
  243. return configType switch
  244. {
  245. ConfigType.c => ClientClassDir,
  246. ConfigType.s => ServerClassDir,
  247. _ => CSClassDir
  248. };
  249. }
  250. // 动态编译生成的cs代码
  251. private static Assembly DynamicBuild(ConfigType configType)
  252. {
  253. string classPath = GetClassDir(configType);
  254. List<SyntaxTree> syntaxTrees = new List<SyntaxTree>();
  255. List<string> protoNames = new List<string>();
  256. foreach (string classFile in Directory.GetFiles(classPath, "*.cs"))
  257. {
  258. protoNames.Add(Path.GetFileNameWithoutExtension(classFile));
  259. syntaxTrees.Add(CSharpSyntaxTree.ParseText(File.ReadAllText(classFile)));
  260. }
  261. List<PortableExecutableReference> references = new List<PortableExecutableReference>();
  262. Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
  263. foreach (Assembly assembly in assemblies)
  264. {
  265. try
  266. {
  267. if (assembly.IsDynamic)
  268. {
  269. continue;
  270. }
  271. if (assembly.Location == "")
  272. {
  273. continue;
  274. }
  275. }
  276. catch (Exception e)
  277. {
  278. Console.WriteLine(e);
  279. throw;
  280. }
  281. PortableExecutableReference reference = MetadataReference.CreateFromFile(assembly.Location);
  282. references.Add(reference);
  283. }
  284. CSharpCompilation compilation = CSharpCompilation.Create(null,
  285. syntaxTrees.ToArray(),
  286. references.ToArray(),
  287. new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
  288. using MemoryStream memSteam = new MemoryStream();
  289. EmitResult emitResult = compilation.Emit(memSteam);
  290. if (!emitResult.Success)
  291. {
  292. StringBuilder stringBuilder = new StringBuilder();
  293. foreach (Diagnostic t in emitResult.Diagnostics)
  294. {
  295. stringBuilder.Append($"{t.GetMessage()}\n");
  296. }
  297. throw new Exception($"动态编译失败:\n{stringBuilder}");
  298. }
  299. memSteam.Seek(0, SeekOrigin.Begin);
  300. Assembly ass = Assembly.Load(memSteam.ToArray());
  301. return ass;
  302. }
  303. #region 导出class
  304. static void ExportExcelClass(ExcelPackage p, string name, Table table)
  305. {
  306. foreach (ExcelWorksheet worksheet in p.Workbook.Worksheets)
  307. {
  308. ExportSheetClass(worksheet, table);
  309. }
  310. }
  311. static void ExportSheetClass(ExcelWorksheet worksheet, Table table)
  312. {
  313. const int row = 2;
  314. for (int col = 3; col <= worksheet.Dimension.End.Column; ++col)
  315. {
  316. if (worksheet.Name.StartsWith("#"))
  317. {
  318. continue;
  319. }
  320. string fieldName = worksheet.Cells[row + 2, col].Text.Trim();
  321. if (fieldName == "")
  322. {
  323. continue;
  324. }
  325. if (table.HeadInfos.ContainsKey(fieldName))
  326. {
  327. continue;
  328. }
  329. string fieldCS = worksheet.Cells[row, col].Text.Trim().ToLower();
  330. if (fieldCS.Contains("#"))
  331. {
  332. table.HeadInfos[fieldName] = null;
  333. continue;
  334. }
  335. if (fieldCS == "")
  336. {
  337. fieldCS = "cs";
  338. }
  339. if (table.HeadInfos.TryGetValue(fieldName, out var oldClassField))
  340. {
  341. if (oldClassField.FieldCS != fieldCS)
  342. {
  343. Log.Console($"field cs not same: {worksheet.Name} {fieldName} oldcs: {oldClassField.FieldCS} {fieldCS}");
  344. }
  345. continue;
  346. }
  347. string fieldDesc = worksheet.Cells[row + 1, col].Text.Trim();
  348. string fieldType = worksheet.Cells[row + 3, col].Text.Trim();
  349. table.HeadInfos[fieldName] = new HeadInfo(fieldCS, fieldDesc, fieldName, fieldType, ++table.Index);
  350. }
  351. }
  352. static void ExportClass(string protoName, Dictionary<string, HeadInfo> classField, ConfigType configType)
  353. {
  354. string dir = GetClassDir(configType);
  355. if (!Directory.Exists(dir))
  356. {
  357. Directory.CreateDirectory(dir);
  358. }
  359. string exportPath = Path.Combine(dir, $"{protoName}.cs");
  360. using FileStream txt = new FileStream(exportPath, FileMode.Create);
  361. using StreamWriter sw = new StreamWriter(txt);
  362. StringBuilder sb = new StringBuilder();
  363. foreach ((string _, HeadInfo headInfo) in classField)
  364. {
  365. if (headInfo == null)
  366. {
  367. continue;
  368. }
  369. if (configType != ConfigType.cs && !headInfo.FieldCS.Contains(configType.ToString()))
  370. {
  371. continue;
  372. }
  373. sb.Append($"\t\t/// <summary>{headInfo.FieldDesc}</summary>\n");
  374. string fieldType = headInfo.FieldType;
  375. sb.Append($"\t\tpublic {fieldType} {headInfo.FieldName} {{ get; set; }}\n");
  376. }
  377. string content = template.Replace("(ConfigName)", protoName).Replace(("(Fields)"), sb.ToString());
  378. sw.Write(content);
  379. }
  380. #endregion
  381. #region 导出json
  382. static void ExportExcelJson(ExcelPackage p, string name, Table table, ConfigType configType, string relativeDir)
  383. {
  384. StringBuilder sb = new StringBuilder();
  385. sb.Append("{\"dict\": [\n");
  386. foreach (ExcelWorksheet worksheet in p.Workbook.Worksheets)
  387. {
  388. if (worksheet.Name.StartsWith("#"))
  389. {
  390. continue;
  391. }
  392. ExportSheetJson(worksheet, name, table.HeadInfos, configType, sb);
  393. }
  394. sb.Append("]}\n");
  395. string dir = string.Format(jsonDir, configType.ToString(), relativeDir);
  396. if (!Directory.Exists(dir))
  397. {
  398. Directory.CreateDirectory(dir);
  399. }
  400. string jsonPath = Path.Combine(dir, $"{name}.txt");
  401. using FileStream txt = new FileStream(jsonPath, FileMode.Create);
  402. using StreamWriter sw = new StreamWriter(txt);
  403. sw.Write(sb.ToString());
  404. }
  405. static void ExportSheetJson(ExcelWorksheet worksheet, string name,
  406. Dictionary<string, HeadInfo> classField, ConfigType configType, StringBuilder sb)
  407. {
  408. string configTypeStr = configType.ToString();
  409. for (int row = 6; row <= worksheet.Dimension.End.Row; ++row)
  410. {
  411. string prefix = worksheet.Cells[row, 2].Text.Trim();
  412. if (prefix.Contains("#"))
  413. {
  414. continue;
  415. }
  416. if (prefix == "")
  417. {
  418. prefix = "cs";
  419. }
  420. if (configType != ConfigType.cs && !prefix.Contains(configTypeStr))
  421. {
  422. continue;
  423. }
  424. if (worksheet.Cells[row, 3].Text.Trim() == "")
  425. {
  426. continue;
  427. }
  428. sb.Append($"[{worksheet.Cells[row, 3].Text.Trim()}, {{\"_t\":\"{name}\"");
  429. for (int col = 3; col <= worksheet.Dimension.End.Column; ++col)
  430. {
  431. string fieldName = worksheet.Cells[4, col].Text.Trim();
  432. if (!classField.ContainsKey(fieldName))
  433. {
  434. continue;
  435. }
  436. HeadInfo headInfo = classField[fieldName];
  437. if (headInfo == null)
  438. {
  439. continue;
  440. }
  441. if (configType != ConfigType.cs && !headInfo.FieldCS.Contains(configTypeStr))
  442. {
  443. continue;
  444. }
  445. string fieldN = headInfo.FieldName;
  446. if (fieldN == "Id")
  447. {
  448. fieldN = "_id";
  449. }
  450. sb.Append($",\"{fieldN}\":{Convert(headInfo.FieldType, worksheet.Cells[row, col].Text.Trim())}");
  451. }
  452. sb.Append("}],\n");
  453. }
  454. }
  455. private static string Convert(string type, string value)
  456. {
  457. switch (type)
  458. {
  459. case "uint[]":
  460. case "int[]":
  461. case "int32[]":
  462. case "long[]":
  463. return $"[{value}]";
  464. case "string[]":
  465. case "int[][]":
  466. return $"[{value}]";
  467. case "int":
  468. case "uint":
  469. case "int32":
  470. case "int64":
  471. case "long":
  472. case "float":
  473. case "double":
  474. if (value == "")
  475. {
  476. return "0";
  477. }
  478. return value;
  479. case "string":
  480. value = value.Replace("\\", "\\\\");
  481. value = value.Replace("\"", "\\\"");
  482. return $"\"{value}\"";
  483. default:
  484. throw new Exception($"不支持此类型: {type}");
  485. }
  486. }
  487. #endregion
  488. // 根据生成的类,把json转成protobuf
  489. private static void ExportExcelProtobuf(ConfigType configType, string protoName, string relativeDir)
  490. {
  491. string dir = GetProtoDir(configType, relativeDir);
  492. if (!Directory.Exists(dir))
  493. {
  494. Directory.CreateDirectory(dir);
  495. }
  496. Assembly ass = GetAssembly(configType);
  497. Type type = ass.GetType($"ET.{protoName}Category");
  498. Type subType = ass.GetType($"ET.{protoName}");
  499. IMerge final = Activator.CreateInstance(type) as IMerge;
  500. string p = Path.Combine(string.Format(jsonDir, configType, relativeDir));
  501. string[] ss = Directory.GetFiles(p, $"{protoName}*.txt");
  502. List<string> jsonPaths = ss.ToList();
  503. jsonPaths.Sort();
  504. jsonPaths.Reverse();
  505. foreach (string jsonPath in jsonPaths)
  506. {
  507. string json = File.ReadAllText(jsonPath);
  508. try
  509. {
  510. object deserialize = BsonSerializer.Deserialize(json, type);
  511. final.Merge(deserialize);
  512. }
  513. catch (Exception e)
  514. {
  515. throw new Exception($"json : {jsonPath} error", e);
  516. }
  517. }
  518. string path = Path.Combine(dir, $"{protoName}Category.bytes");
  519. using FileStream file = File.Create(path);
  520. file.Write(final.ToBson());
  521. }
  522. }
  523. }