ExcelExporter.cs 22 KB

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