Mapping.cs 1.4 KB

12345678910111213141516171819202122232425262728293031323334
  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. var position = property.GetCustomAttributes(typeof(ColumnAttribute), false).FirstOrDefault() is ColumnAttribute { Names.Length: > 0 } columnAttribute
  17. ?
  18. headerCells.FirstOrDefault(x => !x.Value.IsBlank && Array.Exists(columnAttribute.Names, y => y.Equals(x.Value.ToString(), StringComparison.InvariantCultureIgnoreCase)))?.Address.ColumnNumber
  19. : headerCells.FirstOrDefault(x => !x.Value.IsBlank && x.Value.ToString().Equals(property.Name, StringComparison.InvariantCultureIgnoreCase))?.Address.ColumnNumber;
  20. if (position == null) continue;
  21. map.Add(new Mapping { PropertyName = property.Name, Position = position });
  22. }
  23. if (map.Count == properties.Length)
  24. return map;
  25. return null;
  26. }
  27. }
  28. }