ExcelExporter.cs 22 KB

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