ExcelExporter.cs 13 KB

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