ExcelExporter.cs 22 KB

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