ExcelExporter.cs 22 KB

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