ExcelExporter.cs 23 KB

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