diff --git a/ExcelMapper.Tests/Tests.cs b/ExcelMapper.Tests/Tests.cs index 28b2f9d..28e4bd0 100644 --- a/ExcelMapper.Tests/Tests.cs +++ b/ExcelMapper.Tests/Tests.cs @@ -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().ToList(); + + CollectionAssert.AreEqual(new List + { + 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().ToList(); + + CollectionAssert.AreEqual(products, productsFetched); + } } } diff --git a/ExcelMapper/ColumnInfo.cs b/ExcelMapper/ColumnInfo.cs index 77c87f4..5349e7b 100644 --- a/ExcelMapper/ColumnInfo.cs +++ b/ExcelMapper/ColumnInfo.cs @@ -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) @@ -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); + } + /// /// Computes value that can be assigned to property from cell value. /// @@ -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);