Mapping.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. using System.Reflection;
  2. using ClosedXML.Excel;
  3. using ExcelORM.Attributes;
  4. namespace ExcelORM
  5. {
  6. public class Mapping
  7. {
  8. public string? PropertyName { get; set; }
  9. public int? Position { get; set; }
  10. private static int? GetColumnPosition(IXLCells headerCells, PropertyInfo property, bool fallbackToPropertyName)
  11. {
  12. int? position = null;
  13. var columnAttributeObject = property.GetCustomAttributes(typeof(ColumnAttribute), false).FirstOrDefault();
  14. if (columnAttributeObject != null)
  15. {
  16. if (columnAttributeObject is ColumnAttribute { Names.Length: > 0 } columnAttribute)
  17. {
  18. position = headerCells.FirstOrDefault(x => !x.Value.IsBlank && Array.Exists(columnAttribute.Names,
  19. y => y.Equals(x.Value.ToString(), StringComparison.OrdinalIgnoreCase)))?.Address
  20. .ColumnNumber;
  21. }
  22. if (position != null || !fallbackToPropertyName) return position;
  23. }
  24. return headerCells.FirstOrDefault(x =>
  25. !x.Value.IsBlank &&
  26. property.Name.Equals(x.Value.ToString(), StringComparison.OrdinalIgnoreCase))?.Address
  27. .ColumnNumber;
  28. }
  29. public static List<Mapping> MapProperties<T>(IXLCells? headerCells, bool fallbackToPropertyName = false) where T : class
  30. {
  31. var map = new List<Mapping>();
  32. if (headerCells == null || !headerCells.Any()) return map;
  33. var properties = typeof(T).GetProperties();
  34. foreach (var property in properties)
  35. {
  36. if (property.Skip()) continue;
  37. var position = GetColumnPosition(headerCells, property, fallbackToPropertyName);
  38. if (position == null) continue;
  39. map.Add(new Mapping { PropertyName = property.Name, Position = position });
  40. }
  41. return map;
  42. }
  43. }
  44. }