ExcelExporter.cs 13 KB

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