TypeExtensions.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. using System.Reflection;
  2. using ClosedXML.Excel;
  3. namespace ExcelORM;
  4. public static class TypeExtensions
  5. {
  6. public static void SetValue<T>(this T currentObject, PropertyInfo property, IXLCell cell)
  7. {
  8. object? valueToSet = property.PropertyType switch
  9. {
  10. not null when property.PropertyType == typeof(string) => cell.Value.ToString(),
  11. not null when property.PropertyType == typeof(DateTime?) => cell.Value.IsDateTime ? cell.Value.GetDateTime() : null,
  12. not null when property.PropertyType == typeof(TimeSpan?) => cell.Value.IsTimeSpan ? cell.Value.GetTimeSpan() : null,
  13. not null when property.PropertyType == typeof(double?) => cell.Value.IsNumber ? cell.Value.GetNumber() : null,
  14. not null when property.PropertyType == typeof(int?) => cell.Value.IsNumber ? (int?)cell.Value.GetNumber() : null,
  15. _ => throw new NotSupportedException($"{property.PropertyType} isn't supported!")
  16. };
  17. if (valueToSet != null)
  18. property.SetValue(currentObject, valueToSet);
  19. }
  20. public static void SetCellValue(this IXLCell cell, PropertyInfo property, object? valueToSet)
  21. {
  22. if (valueToSet == null) return;
  23. cell.Value = property.PropertyType switch
  24. {
  25. not null when property.PropertyType == typeof(string) => valueToSet as string,
  26. not null when property.PropertyType == typeof(DateTime?) => valueToSet as DateTime?,
  27. not null when property.PropertyType == typeof(TimeSpan?) => valueToSet as TimeSpan?,
  28. not null when property.PropertyType == typeof(double?) => valueToSet as double?,
  29. not null when property.PropertyType == typeof(int?) => valueToSet as int?,
  30. _ => throw new NotSupportedException($"{property.PropertyType} isn't supported!")
  31. };
  32. }
  33. }