ExcelExporter.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  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 Microsoft.CodeAnalysis;
  8. using Microsoft.CodeAnalysis.CSharp;
  9. using Microsoft.CodeAnalysis.Emit;
  10. using MongoDB.Bson;
  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,
  20. s,
  21. }
  22. class HeadInfo
  23. {
  24. public string FieldAttribute;
  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.FieldAttribute = cs;
  32. this.FieldDesc = desc;
  33. this.FieldName = name;
  34. this.FieldType = type;
  35. this.FieldIndex = index;
  36. }
  37. }
  38. public static class ExcelExporter
  39. {
  40. private static string template;
  41. private const string clientClassDir = "../Unity/Codes/Model/Generate/Config";
  42. private const string serverClassDir = "../Server/Model/Generate/Config";
  43. private const string excelDir = "../Excel";
  44. private const string jsonDir = "./Json/{0}";
  45. private const string clientProtoDir = "../Unity/Assets/Bundles/Config";
  46. private const string serverProtoDir = "../Config";
  47. public static void Export()
  48. {
  49. try
  50. {
  51. template = File.ReadAllText("Template.txt");
  52. ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
  53. Directory.Delete(clientClassDir, true);
  54. Directory.Delete(serverClassDir, true);
  55. foreach (string path in Directory.GetFiles(excelDir))
  56. {
  57. string fileName = Path.GetFileName(path);
  58. if (!fileName.EndsWith(".xlsx") || fileName.StartsWith("~$"))
  59. {
  60. continue;
  61. }
  62. using Stream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
  63. using ExcelPackage p = new ExcelPackage(stream);
  64. string name = Path.GetFileNameWithoutExtension(path);
  65. string cs = p.Workbook.Worksheets[0].Cells[1, 1].Text.Trim();
  66. if (cs.Contains("#"))
  67. {
  68. continue;
  69. }
  70. if (cs == "")
  71. {
  72. cs = "cs";
  73. }
  74. if (cs.Contains("c"))
  75. {
  76. ExportExcelClass(p, name, ConfigType.c);
  77. }
  78. if (cs.Contains("s"))
  79. {
  80. ExportExcelClass(p, name, ConfigType.s);
  81. }
  82. }
  83. ExportExcelProtobuf(ConfigType.c);
  84. ExportExcelProtobuf(ConfigType.s);
  85. Console.WriteLine("导表成功!");
  86. }
  87. catch (Exception e)
  88. {
  89. Console.WriteLine(e);
  90. }
  91. }
  92. private static string GetProtoDir(ConfigType configType)
  93. {
  94. if (configType == ConfigType.c)
  95. {
  96. return clientProtoDir;
  97. }
  98. return serverProtoDir;
  99. }
  100. private static string GetClassDir(ConfigType configType)
  101. {
  102. if (configType == ConfigType.c)
  103. {
  104. return clientClassDir;
  105. }
  106. return serverClassDir;
  107. }
  108. #region 导出class
  109. static void ExportExcelClass(ExcelPackage p, string name, ConfigType configType)
  110. {
  111. Dictionary<string, HeadInfo> classField = new Dictionary<string, HeadInfo>();
  112. foreach (ExcelWorksheet worksheet in p.Workbook.Worksheets)
  113. {
  114. ExportSheetClass(worksheet, classField, configType);
  115. }
  116. ExportClass(name, classField, configType);
  117. ExportExcelJson(p, name, classField, configType);
  118. }
  119. static void ExportSheetClass(ExcelWorksheet worksheet, Dictionary<string, HeadInfo> classField, ConfigType configType)
  120. {
  121. string configTypeStr = configType.ToString();
  122. const int row = 2;
  123. for (int col = 3; col <= worksheet.Dimension.End.Column; ++col)
  124. {
  125. if (worksheet.Name.StartsWith("#"))
  126. {
  127. continue;
  128. }
  129. string fieldName = worksheet.Cells[row + 2, col].Text.Trim();
  130. if (fieldName == "")
  131. {
  132. continue;
  133. }
  134. if (classField.ContainsKey(fieldName))
  135. {
  136. continue;
  137. }
  138. string fieldCS = worksheet.Cells[row, col].Text.Trim().ToLower();
  139. if (fieldCS.Contains("#"))
  140. {
  141. classField[fieldName] = null;
  142. continue;
  143. }
  144. if (fieldCS == "")
  145. {
  146. fieldCS = "cs";
  147. }
  148. if (!fieldCS.Contains(configTypeStr))
  149. {
  150. classField[fieldName] = null;
  151. continue;
  152. }
  153. string fieldDesc = worksheet.Cells[row + 1, col].Text.Trim();
  154. string fieldType = worksheet.Cells[row + 3, col].Text.Trim();
  155. classField[fieldName] = new HeadInfo(fieldCS, fieldDesc, fieldName, fieldType, col);
  156. }
  157. }
  158. static void ExportClass(string protoName, Dictionary<string, HeadInfo> classField, ConfigType configType)
  159. {
  160. string dir = GetClassDir(configType);
  161. if (!Directory.Exists(dir))
  162. {
  163. Directory.CreateDirectory(dir);
  164. }
  165. string exportPath = Path.Combine(dir, $"{protoName}.cs");
  166. using FileStream txt = new FileStream(exportPath, FileMode.Create);
  167. using StreamWriter sw = new StreamWriter(txt);
  168. StringBuilder sb = new StringBuilder();
  169. foreach ((string _, HeadInfo headInfo) in classField)
  170. {
  171. if (headInfo == null)
  172. {
  173. continue;
  174. }
  175. sb.Append($"\t\t[ProtoMember({headInfo.FieldIndex - 2})]\n");
  176. sb.Append($"\t\tpublic {headInfo.FieldType} {headInfo.FieldName} {{ get; set; }}\n");
  177. }
  178. string content = template.Replace("(ConfigName)", protoName).Replace(("(Fields)"), sb.ToString());
  179. sw.Write(content);
  180. }
  181. #endregion
  182. #region 导出json
  183. static void ExportExcelJson(ExcelPackage p, string name, Dictionary<string, HeadInfo> classField, ConfigType configType)
  184. {
  185. StringBuilder sb = new StringBuilder();
  186. sb.AppendLine("{\"list\":[");
  187. foreach (ExcelWorksheet worksheet in p.Workbook.Worksheets)
  188. {
  189. if (worksheet.Name.StartsWith("#"))
  190. {
  191. continue;
  192. }
  193. ExportSheetJson(worksheet, name, classField, configType, sb);
  194. }
  195. sb.AppendLine("]}");
  196. string dir = string.Format(jsonDir, configType.ToString());
  197. if (!Directory.Exists(dir))
  198. {
  199. Directory.CreateDirectory(dir);
  200. }
  201. string jsonPath = Path.Combine(dir, $"{name}.txt");
  202. using FileStream txt = new FileStream(jsonPath, FileMode.Create);
  203. using StreamWriter sw = new StreamWriter(txt);
  204. sw.Write(sb.ToString());
  205. }
  206. static void ExportSheetJson(ExcelWorksheet worksheet, string name, Dictionary<string, HeadInfo> classField, ConfigType configType, StringBuilder sb)
  207. {
  208. string configTypeStr = configType.ToString();
  209. for (int row = 6; row <= worksheet.Dimension.End.Row; ++row)
  210. {
  211. string prefix = worksheet.Cells[row, 2].Text.Trim();
  212. if (prefix.Contains("#"))
  213. {
  214. continue;
  215. }
  216. if (prefix == "")
  217. {
  218. prefix = "cs";
  219. }
  220. if (!prefix.Contains(configTypeStr))
  221. {
  222. continue;
  223. }
  224. if (worksheet.Cells[row, 3].Text.Trim() == "")
  225. {
  226. continue;
  227. }
  228. sb.Append("{");
  229. sb.Append($"\"_t\":\"{name}\"");
  230. for (int col = 3; col <= worksheet.Dimension.End.Column; ++col)
  231. {
  232. string fieldName = worksheet.Cells[4, col].Text.Trim();
  233. if (!classField.ContainsKey(fieldName))
  234. {
  235. continue;
  236. }
  237. HeadInfo headInfo = classField[fieldName];
  238. if (headInfo == null)
  239. {
  240. continue;
  241. }
  242. string fieldN = headInfo.FieldName;
  243. if (fieldN == "Id")
  244. {
  245. fieldN = "_id";
  246. }
  247. sb.Append($",\"{fieldN}\":{Convert(headInfo.FieldType, worksheet.Cells[row, col].Text.Trim())}");
  248. }
  249. sb.Append("},\n");
  250. }
  251. }
  252. private static string Convert(string type, string value)
  253. {
  254. switch (type)
  255. {
  256. case "int[]":
  257. case "int32[]":
  258. case "long[]":
  259. return $"[{value}]";
  260. case "string[]":
  261. return $"[{value}]";
  262. case "int":
  263. case "int32":
  264. case "int64":
  265. case "long":
  266. case "float":
  267. case "double":
  268. if (value == "")
  269. {
  270. return "0";
  271. }
  272. return value;
  273. case "string":
  274. return $"\"{value}\"";
  275. default:
  276. throw new Exception($"不支持此类型: {type}");
  277. }
  278. }
  279. #endregion
  280. // 根据生成的类,动态编译把json转成protobuf
  281. private static void ExportExcelProtobuf(ConfigType configType)
  282. {
  283. string classPath = GetClassDir(configType);
  284. List<SyntaxTree> syntaxTrees = new List<SyntaxTree>();
  285. List<string> protoNames = new List<string>();
  286. foreach (string classFile in Directory.GetFiles(classPath, "*.cs"))
  287. {
  288. protoNames.Add(Path.GetFileNameWithoutExtension(classFile));
  289. syntaxTrees.Add(CSharpSyntaxTree.ParseText(File.ReadAllText(classFile)));
  290. }
  291. List<PortableExecutableReference> references = new List<PortableExecutableReference>();
  292. Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
  293. foreach (Assembly assembly in assemblies)
  294. {
  295. try
  296. {
  297. if (assembly.IsDynamic)
  298. {
  299. continue;
  300. }
  301. if (assembly.Location == "")
  302. {
  303. continue;
  304. }
  305. }
  306. catch (Exception e)
  307. {
  308. Console.WriteLine(e);
  309. throw;
  310. }
  311. PortableExecutableReference reference = MetadataReference.CreateFromFile(assembly.Location);
  312. references.Add(reference);
  313. }
  314. CSharpCompilation compilation = CSharpCompilation.Create(
  315. null,
  316. syntaxTrees.ToArray(),
  317. references.ToArray(),
  318. new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
  319. using MemoryStream memSteam = new MemoryStream();
  320. EmitResult emitResult = compilation.Emit(memSteam);
  321. if (!emitResult.Success)
  322. {
  323. StringBuilder stringBuilder = new StringBuilder();
  324. foreach (Diagnostic t in emitResult.Diagnostics)
  325. {
  326. stringBuilder.AppendLine(t.GetMessage());
  327. }
  328. throw new Exception($"动态编译失败:\n{stringBuilder}");
  329. }
  330. memSteam.Seek(0, SeekOrigin.Begin);
  331. Assembly ass = Assembly.Load(memSteam.ToArray());
  332. string dir = GetProtoDir(configType);
  333. if (!Directory.Exists(dir))
  334. {
  335. Directory.CreateDirectory(dir);
  336. }
  337. foreach (string protoName in protoNames)
  338. {
  339. Type type = ass.GetType($"ET.{protoName}Category");
  340. Type subType = ass.GetType($"ET.{protoName}");
  341. Serializer.NonGeneric.PrepareSerializer(type);
  342. Serializer.NonGeneric.PrepareSerializer(subType);
  343. string json = File.ReadAllText(Path.Combine(string.Format(jsonDir, configType), $"{protoName}.txt"));
  344. object deserialize = BsonSerializer.Deserialize(json, type);
  345. string path = Path.Combine(dir, $"{protoName}Category.bytes");
  346. using FileStream file = File.Create(path);
  347. Serializer.Serialize(file, deserialize);
  348. }
  349. }
  350. }
  351. }