Mapping.cs 1.4 KB

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