ExcelExporter.cs 20 KB

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