From 5be518228f9bb52cab033077b6ddfb8e90be996b Mon Sep 17 00:00:00 2001 From: KaneLeung Date: Mon, 19 Dec 2022 17:16:06 +0800 Subject: [PATCH] Query from enum description. --- .../Attributes/QueryFromDescriptionAttribute.cs | 9 +++++++++ src/MiniExcel/Utils/TypeHelper.cs | 16 +++++++++++----- 2 files changed, 20 insertions(+), 5 deletions(-) create mode 100644 src/MiniExcel/Attributes/QueryFromDescriptionAttribute.cs diff --git a/src/MiniExcel/Attributes/QueryFromDescriptionAttribute.cs b/src/MiniExcel/Attributes/QueryFromDescriptionAttribute.cs new file mode 100644 index 0000000..11bea25 --- /dev/null +++ b/src/MiniExcel/Attributes/QueryFromDescriptionAttribute.cs @@ -0,0 +1,9 @@ +using System; + +namespace MiniExcelLibs.Attributes +{ + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] + public class QueryFromDescriptionAttribute : Attribute + { + } +} \ No newline at end of file diff --git a/src/MiniExcel/Utils/TypeHelper.cs b/src/MiniExcel/Utils/TypeHelper.cs index ff28ddc..0cf8b5e 100644 --- a/src/MiniExcel/Utils/TypeHelper.cs +++ b/src/MiniExcel/Utils/TypeHelper.cs @@ -4,16 +4,15 @@ using MiniExcelLibs.Exceptions; using System; using System.Collections.Generic; + using System.ComponentModel; using System.Data; - using System.Dynamic; using System.Globalization; - using System.IO; using System.Linq; using System.Reflection; internal static partial class TypeHelper { - public static IEnumerable> ConvertToEnumerableDictionary(IDataReader reader) + public static IEnumerable> ConvertToEnumerableDictionary(IDataReader reader) { while (reader.Read()) { @@ -109,7 +108,7 @@ private static object TypeMappingImpl(T v, ExcelColumnInfo pInfo, ref object var vs = itemValue?.ToString(); if (pInfo.ExcelFormat != null) { - if( pInfo.Property.PropertyType == typeof(DateTimeOffset) && DateTimeOffset.TryParseExact(vs, pInfo.ExcelFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out var _v2)) + if (pInfo.Property.PropertyType == typeof(DateTimeOffset) && DateTimeOffset.TryParseExact(vs, pInfo.ExcelFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out var _v2)) { newValue = _v2; } @@ -143,7 +142,14 @@ private static object TypeMappingImpl(T v, ExcelColumnInfo pInfo, ref object } else if (pInfo.Property.PropertyType.IsEnum) { - newValue = Enum.Parse(pInfo.Property.PropertyType, itemValue?.ToString(), true); + var enumFromDesc = pInfo.Property.GetAttribute(); + if (enumFromDesc != null) + { + var fieldInfo = pInfo.Property.PropertyType.GetFields().FirstOrDefault(e => e.GetCustomAttribute(false)?.Description == itemValue?.ToString()); + if (fieldInfo != null) newValue = Enum.Parse(pInfo.Property.PropertyType, fieldInfo.Name, true); + else Enum.Parse(pInfo.Property.PropertyType, itemValue?.ToString(), true); + } + else newValue = Enum.Parse(pInfo.Property.PropertyType, itemValue?.ToString(), true); } else { -- Gitee