ExcelExporter.cs 23 KB

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