Mapping.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. using ClosedXML.Excel;
  2. using ExcelORM.Attributes;
  3. namespace ExcelORM
  4. {
  5. public class Mapping
  6. {
  7. public string? PropertyName { get; set; }
  8. public int? Position { get; set; }
  9. public static List<Mapping>? MapProperties<T>(IXLCells? headerCells) where T : new()
  10. {
  11. if (headerCells == null || !headerCells.Any()) return null;
  12. var map = new List<Mapping>();
  13. var properties = typeof(T).GetProperties();
  14. foreach (var property in properties)
  15. {
  16. int? position;
  17. var attribute =
  18. property.GetCustomAttributes(typeof(ColumnAttribute), false).FirstOrDefault() as ColumnAttribute;
  19. if (attribute is { Names.Length: > 0 })
  20. position = headerCells.FirstOrDefault(x => !x.Value.IsBlank && Array.Exists(attribute.Names,
  21. y => y.Equals(x.Value.ToString(), StringComparison.InvariantCultureIgnoreCase)))?.Address
  22. .ColumnNumber;
  23. else
  24. position = headerCells.FirstOrDefault(x => !x.Value.IsBlank && property.Name.Equals(x.Value.ToString(), StringComparison.InvariantCultureIgnoreCase))?.Address.ColumnNumber;
  25. if (position == null) continue;
  26. map.Add(new Mapping { PropertyName = property.Name, Position = position });
  27. }
  28. return map.Count == properties.Length ? map : null;
  29. }
  30. }
  31. }