Skip to content

Commit

Permalink
Add support for mapping to enum properties from string values (fixes #…
Browse files Browse the repository at this point in the history
  • Loading branch information
Michael Ganss committed Apr 19, 2022
1 parent 7efee41 commit 92e9fe2
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
36 changes: 36 additions & 0 deletions ExcelMapper.Tests/Tests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2589,5 +2589,41 @@ public void AttachWithWorkbookUsingFetchTest()
new Product { Name = "Filinchen", NumberInStock = 100, Price = 0.99m, Value = "C5*D5" },
}, products);
}

private enum NameEnum
{
Nudossi,
Halloren,
Filinchen
}

private record EnumProduct
{
public NameEnum Name { get; }

public EnumProduct(NameEnum name) => Name = name;
}

[Test]
public void EnumTest()
{
var excel = new ExcelMapper("../../../Products.xlsx");
var products = excel.Fetch<EnumProduct>().ToList();

CollectionAssert.AreEqual(new List<EnumProduct>
{
new EnumProduct(NameEnum.Nudossi),
new EnumProduct(NameEnum.Halloren),
new EnumProduct(NameEnum.Filinchen),
}, products);

var file = "enumsave.xlsx";

excel.Save(file, products, "Products");

var productsFetched = new ExcelMapper(file).Fetch<EnumProduct>().ToList();

CollectionAssert.AreEqual(products, productsFetched);
}
}
}
9 changes: 9 additions & 0 deletions ExcelMapper/ColumnInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ internal void SetPropertyType(Type propertyType)

isSubType = PropertyType != null
&& !PropertyType.IsPrimitive
&& !PropertyType.IsEnum
&& PropertyType != typeof(decimal)
&& PropertyType != typeof(string)
&& PropertyType != typeof(DateTime)
Expand Down Expand Up @@ -237,6 +238,12 @@ public void SetCellStyle(ICell c)
c.CellStyle = c.Sheet.GetColumnStyle(c.ColumnIndex);
}

private object ParseEnum(Type t, string s)
{
var name = Enum.GetNames(t).FirstOrDefault(n => n.Equals(s, StringComparison.OrdinalIgnoreCase));
return name == null ? Activator.CreateInstance(t) : Enum.Parse(t, name);
}

/// <summary>
/// Computes value that can be assigned to property from cell value.
/// </summary>
Expand All @@ -253,6 +260,8 @@ public virtual object GetPropertyValue(object o, object val, ICell cell)
v = null;
else if (val is string g && PropertyType == typeof(Guid))
v = Guid.Parse(g);
else if (val is string es && PropertyType.IsEnum)
v = ParseEnum(PropertyType, es);
else
v = Convert.ChangeType(val, PropertyType, CultureInfo.InvariantCulture);

Expand Down

0 comments on commit 92e9fe2

Please sign in to comment.