ExcelExporter.cs 21 KB

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