ExcelExporter.cs 23 KB

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