ExcelExporter.cs 13 KB

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