GeneratorCmd.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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.DateTime => "DateTime?",
  25. XLDataType.TimeSpan => "TimeSpan?",
  26. _ => throw new Exception($"Can't match {type}!")
  27. };
  28. private static void GenerateRecord(WorksheetRecord worksheet, string outputFolder, string filename)
  29. {
  30. var recordObject = new ClassRecordGenerator(filename, worksheet.Name, true);
  31. var outputPath = Path.Combine(outputFolder, $"{recordObject.Name}.cs");
  32. recordObject.Usings.Add("ExcelORM");
  33. foreach (var column in worksheet.Columns)
  34. {
  35. if (string.IsNullOrWhiteSpace(column.Name)) continue;
  36. var propertyObject = new Property(column.Name, GetType(column.Type));
  37. propertyObject.Attributes.Add(new AttributeElement("Column", column.Name));
  38. if (column.Type == XLDataType.DateTime) recordObject.Usings.Add("System");
  39. if (!recordObject.Properties.TryAdd(propertyObject.Name, propertyObject))
  40. Console.Error.WriteLine($"Duplicated property {propertyObject.Name}!");
  41. }
  42. File.WriteAllText(outputPath, recordObject.Build());
  43. }
  44. private static void Generate(Settings settings)
  45. {
  46. if (string.IsNullOrWhiteSpace(settings.InputPath)) return;
  47. var worksheetsInfo = WorkbookInfo.GetInfoOnWorksheets(settings.InputPath, settings.StartFrom).ToArray();
  48. if (worksheetsInfo.Length == 0) throw new Exception("Nothing to process!");
  49. var outputFolder = Path.GetDirectoryName(settings.InputPath);
  50. if (string.IsNullOrWhiteSpace(outputFolder))
  51. throw new Exception($"Can't establish folder from {settings.InputPath}!");
  52. var filename = Path.GetFileNameWithoutExtension(settings.InputPath);
  53. foreach(var worksheet in worksheetsInfo)
  54. GenerateRecord(worksheet, outputFolder, filename);
  55. }
  56. public override int Execute(CommandContext context, Settings settings)
  57. {
  58. if (!File.Exists(settings.InputPath)) throw new FileNotFoundException(settings.InputPath);
  59. Generate(settings);
  60. return 0;
  61. }
  62. }