MiniExcel
MiniExcel copied to clipboard
模板导出能否支持嵌套类?
比如A.B.C ,现在只支持集合下面的类属性,嵌套类下面的无法导出
This is not supported at the moment and likely won't be worked on in the foreseeable future. If you could please share a sample of your code explaining what you're trying to achieve we might be able to suggest a workaround for you.
There is a temporary solution to expand nested classes into the class_property form. You need to modify the NeedExpand function.
public static class ObjectToDictionaryConverter
{
public static Dictionary<string, object> ExpandToDictionary(this object obj)
{
if (obj == null) return new Dictionary<string, object>();
var dictionary = new Dictionary<string, object>();
var type = obj.GetType();
foreach (var property in GetProperties(type))
{
var value = property.GetValue(obj);
if (value == null)
{
dictionary.Add(property.Name, null);
continue;
}
if (value is IEnumerable enumerable && !(value is string))
{
var list = new List<object>();
foreach (var item in enumerable)
{
if (item is null)
continue;
else if (NeedExpand(item.GetType()))
list.Add(ExpandToDictionary(item));
else
list.Add((item));
}
dictionary.Add($"{property.Name}", list);
}
else if (NeedExpand(property.PropertyType))//(!IsSimpleType(property.PropertyType))
{
var innerDict = ExpandToDictionary(value);
dictionary.Add($"{property.Name}", value.ToString() ?? "");
foreach (var innerPair in innerDict)
{
dictionary.Add($"{property.Name}_{innerPair.Key}", innerPair.Value);
}
}
else
dictionary.Add(property.Name, value);
}
return dictionary;
}
private static bool NeedExpand(Type type)
{
//if (type == typeof(CoolingPeriodInfo))
/// return false;
if (type.FullName!.StartsWith("FMO"))
return true;
return false;
}
//private static bool IsSimpleType(Type type)
//{
// // 处理可空类型
// if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
// {
// type = Nullable.GetUnderlyingType(type);
// }
// // 基本类型
// if (type.IsPrimitive ||
// type == typeof(string) ||
// type == typeof(decimal) ||
// type == typeof(DateTime) ||
// type == typeof(DateTimeOffset) ||
// type == typeof(TimeSpan) ||
// type == typeof(Guid) ||
// type.IsEnum)
// {
// return true;
// }
// // 数组和集合
// if (typeof(IEnumerable).IsAssignableFrom(type))
// {
// return true;
// }
// return false;
//}
private static IEnumerable<PropertyInfo> GetProperties(Type type)
{
return type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
}
}