GeneratorCmd.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using System.ComponentModel;
  2. using ClosedXML.Excel;
  3. using CodeGenerators;
  4. using ExcelInfo;
  5. using Spectre.Cli;
  6. namespace GeneratorForExcelORM;
  7. internal sealed class GeneratorCmd : Command<GeneratorCmd.Settings>
  8. {
  9. public sealed class Settings : CommandSettings
  10. {
  11. [Description("Path to XLSX file.")]
  12. [CommandArgument(0, "[inputPath]")]
  13. public string? InputPath { get; init; }
  14. [Description("Start from n row. Default 1.")]
  15. [DefaultValue((uint)1)]
  16. [CommandOption("-s|--startFrom")]
  17. public uint StartFrom { get; init; }
  18. }
  19. private static string GetType(XLDataType type) =>
  20. type switch
  21. {
  22. XLDataType.Number => "double?",
  23. XLDataType.Text => "string?",
  24. XLDataType.Blank => "string?",
  25. XLDataType.DateTime => "DateTime?",
  26. XLDataType.TimeSpan => "TimeSpan?",
  27. _ => throw new Exception($"Can't match {type}!")
  28. };
  29. private static void GenerateRecord(WorksheetRecord worksheet, string outputFolder, string filename)
  30. {
  31. var recordObject = new ClassRecordGenerator(filename, worksheet.Name, true);
  32. var outputPath = Path.Combine(outputFolder, $"{recordObject.Name}.cs");
  33. recordObject.Usings.Add("ExcelORM");
  34. foreach (var column in worksheet.Columns)
  35. {
  36. if (string.IsNullOrWhiteSpace(column.Name)) continue;
  37. var propertyObject = new Property(column.Name, GetType(column.Type));
  38. propertyObject.Attributes.Add(new AttributeElement("Column", column.Name));
  39. if (column.Type == XLDataType.DateTime) recordObject.Usings.Add("System");
  40. if (!recordObject.Properties.TryAdd(propertyObject.Name, propertyObject))
  41. Console.Error.WriteLine($"Duplicated property {propertyObject.Name}!");
  42. }
  43. File.WriteAllText(outputPath, recordObject.Build());
  44. }
  45. private static void Generate(Settings settings)
  46. {
  47. if (string.IsNullOrWhiteSpace(settings.InputPath)) return;
  48. var worksheetsInfo = WorkbookInfo.GetInfoOnWorksheets(settings.InputPath, settings.StartFrom).ToArray();
  49. if (worksheetsInfo.Length == 0) throw new Exception("Nothing to process!");
  50. var outputFolder = Path.GetDirectoryName(settings.InputPath);
  51. if (string.IsNullOrWhiteSpace(outputFolder))
  52. throw new Exception($"Can't establish folder from {settings.InputPath}!");
  53. var filename = Path.GetFileNameWithoutExtension(settings.InputPath);
  54. foreach(var worksheet in worksheetsInfo)
  55. GenerateRecord(worksheet, outputFolder, filename);
  56. }
  57. public override int Execute(CommandContext context, Settings settings)
  58. {
  59. if (!File.Exists(settings.InputPath)) throw new FileNotFoundException(settings.InputPath);
  60. Generate(settings);
  61. return 0;
  62. }
  63. }