ExcelExporter.cs 22 KB

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