Newer
Older
DungeonShooting / DungeonShooting_Godot / src / framework / generator / ExcelGenerator.cs
  1. using System.Data;
  2. using System.IO;
  3. using Godot;
  4. using NPOI.XSSF.UserModel;
  5.  
  6. namespace Generator;
  7.  
  8. public static class ExcelGenerator
  9. {
  10. // private class ExcelTableData
  11. // {
  12. // public string[] ColumnName;
  13. // public string[] TypeName;
  14. // public string[][] Data;
  15. // }
  16. public static bool ExportExcel()
  17. {
  18. GD.Print("准备导出excel表...");
  19. var directoryInfo = new DirectoryInfo(GameConfig.ExcelFilePath);
  20. if (directoryInfo.Exists)
  21. {
  22. var fileInfos = directoryInfo.GetFiles();
  23. foreach (var fileInfo in fileInfos)
  24. {
  25. if (fileInfo.Extension == ".xlsx")
  26. {
  27. GD.Print("excel表: " + fileInfo.FullName);
  28. ReadExcel(fileInfo.FullName);
  29. }
  30. }
  31. }
  32.  
  33. return true;
  34. }
  35.  
  36. private static void ReadExcel(string excelPath)
  37. {
  38. var fileName = Path.GetFileNameWithoutExtension(excelPath).FirstToUpper();
  39. var outStr = "namespace Config;\n\n";
  40. outStr += $"public class {fileName} \n{{\n";
  41. var sourceFile = excelPath;
  42. //加载表数据
  43. var workbook = new XSSFWorkbook(sourceFile);
  44. var sheet1 = workbook.GetSheet("Sheet1");
  45.  
  46. //解析表
  47. var rowCount = sheet1.LastRowNum;
  48. //先解析表中的列名, 注释, 类型
  49. var columnCount = -1;
  50. var names = sheet1.GetRow(0);
  51. var descriptions = sheet1.GetRow(1);
  52. var types = sheet1.GetRow(2);
  53. foreach (var cell in names)
  54. {
  55. var value = cell.StringCellValue;
  56. if (string.IsNullOrEmpty(value))
  57. {
  58. columnCount = cell.ColumnIndex;
  59. break;
  60. }
  61.  
  62. value = value.FirstToUpper();
  63. outStr += $" /// <summary>\n";
  64. var descriptionCell = descriptions.GetCell(cell.ColumnIndex);
  65. var description = descriptionCell.StringCellValue.Replace("\n", " <br/>\n /// ");
  66. var type = TypeMapping(types.GetCell(cell.ColumnIndex).StringCellValue);
  67. outStr += $" /// {description}\n";
  68. outStr += $" /// </summary>\n";
  69. outStr += $" public {type} {value};\n\n";
  70. }
  71.  
  72. outStr += "}";
  73. workbook.Close();
  74.  
  75. if (!Directory.Exists("src/config"))
  76. {
  77. Directory.CreateDirectory("src/config");
  78. }
  79. File.WriteAllText("src/config/" + fileName + ".cs", outStr);
  80. }
  81.  
  82. private static string TypeMapping(string typeName)
  83. {
  84. switch (typeName)
  85. {
  86. case "boolean": return "bool";
  87. case "boolean[]": return "bool[]";
  88. case "vector2": return "Godot.Vector2";
  89. case "vector2[]": return "Godot.Vector2[]";
  90. case "vector3": return "Godot.Vector3";
  91. case "vector3[]": return "Godot.Vector3[]";
  92. case "color[]": return "Godot.Color[]";
  93. }
  94.  
  95. return typeName;
  96. }
  97. }