Skip to content

Commit

Permalink
Export supports valuemapping #16 #106
Browse files Browse the repository at this point in the history
  • Loading branch information
hueifeng committed Sep 13, 2020
1 parent 7daef12 commit d910c82
Show file tree
Hide file tree
Showing 6 changed files with 101 additions and 57 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,8 @@ public static string GetDisplayName(this ICustomAttributeProvider customAttribut
public static string GetDisplayFormat(this ICustomAttributeProvider customAttributeProvider)
{
var formatAttribute = customAttributeProvider.GetAttribute<DisplayFormatAttribute>();
string displayFormat=string.Empty;
if (formatAttribute!=null)
string displayFormat = string.Empty;
if (formatAttribute != null)
{
displayFormat = formatAttribute.DataFormatString;
}
Expand Down Expand Up @@ -262,7 +262,7 @@ public static string GetCSharpTypeName(this Type type)
sb.Append("<");
sb.Append(string.Join(", ", type.GetGenericArguments()
.Select(t => t.GetCSharpTypeName())));

sb.Append(">");
return sb.ToString();
}
Expand All @@ -277,7 +277,7 @@ public static object[] CreateType(this Type type)
//Get the first
var constructorInfo = type.GetConstructors().FirstOrDefault();
var parameterInfos = constructorInfo?.GetParameters();
var objects=new List<object>();
var objects = new List<object>();
//GetAssemblies need to add conditional screening
//var getAssemblies = AppDomain.CurrentDomain.GetAssemblies();
List<Type> types = new List<Type>();
Expand Down Expand Up @@ -331,7 +331,7 @@ public static IList<Assembly> GetAllAssemblies()
#else
return AppDomain.CurrentDomain.GetAssemblies();
#endif

}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,6 @@ public class ExporterHeaderInfo

/// <summary>
/// </summary>
public Dictionary<string, dynamic> MappingValues { get; set; } = new Dictionary<string, dynamic>();
public Dictionary<dynamic, string> MappingValues { get; set; } = new Dictionary<dynamic, string>();
}
}
130 changes: 82 additions & 48 deletions src/Magicodes.ExporterAndImporter.Excel/Utility/ExportHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using OfficeOpenXml.Table;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Linq;
Expand All @@ -17,6 +18,8 @@
using OfficeOpenXml.Drawing;
using OfficeOpenXml.Style;
using System.Globalization;
using System.Linq.Expressions;
using System.Reflection;

namespace Magicodes.ExporterAndImporter.Excel.Utility
{
Expand Down Expand Up @@ -270,22 +273,6 @@ protected virtual void GetExporterHeaderInfoList(DataTable dt = null, ICollectio
CsTypeName = keys[i].GetType().GetCSharpTypeName(),
DisplayName = keys[i]
};

if (keys[i].GetType().IsEnum)
{
var type = keys[i].GetType();
var isNullable = type.IsNullable();
if (isNullable) type = type.GetNullableUnderlyingType();
var values = type.GetEnumTextAndValues();

foreach (var value in values.Where(value => !item.MappingValues.ContainsKey(value.Key)))
item.MappingValues.Add(value.Key, value.Value);

if (isNullable)
if (!item.MappingValues.ContainsKey(string.Empty))
item.MappingValues.Add(string.Empty, null);

}
AddExportHeaderInfo(item);
}
}
Expand Down Expand Up @@ -325,20 +312,29 @@ protected virtual void GetExporterHeaderInfoList(DataTable dt = null, ICollectio
(objProperties[i].GetAttribute<IEIgnoreAttribute>(true) == null) ?
item.ExporterHeaderAttribute.IsIgnore : objProperties[i].GetAttribute<IEIgnoreAttribute>(true).IsExportIgnore;

if (objProperties[i].PropertyType.IsEnum)
var mappings = objProperties[i].GetAttributes<ValueMappingAttribute>().ToList();
foreach (var mappingAttribute in mappings.Where(mappingAttribute =>
!item.MappingValues.ContainsKey(mappingAttribute.Value)))
item.MappingValues.Add(mappingAttribute.Value, mappingAttribute.Text);

//如果存在自定义映射,则不会生成默认映射
if (!mappings.Any())
{
var propType = objProperties[i].PropertyType;
var isNullable = propType.IsNullable();
if (isNullable) propType = propType.GetNullableUnderlyingType();
var values = propType.GetEnumTextAndValues();
if (objProperties[i].PropertyType.IsEnum)
{
var propType = objProperties[i].PropertyType;
var isNullable = propType.IsNullable();
if (isNullable) propType = propType.GetNullableUnderlyingType();
var values = propType.GetEnumTextAndValues();

foreach (var value in values.Where(value => !item.MappingValues.ContainsKey(value.Key)))
item.MappingValues.Add(value.Key, value.Value);
foreach (var value in values.Where(value => !item.MappingValues.ContainsKey(value.Key)))
item.MappingValues.Add(value.Value, value.Key);

if (isNullable)
if (!item.MappingValues.ContainsKey(string.Empty))
item.MappingValues.Add(string.Empty, null);
if (isNullable)
if (!item.MappingValues.ContainsKey(string.Empty))
item.MappingValues.Add(string.Empty, null);

}
}

AddExportHeaderInfo(item);
Expand Down Expand Up @@ -375,8 +371,15 @@ public virtual void SetExporterHeaderFilter(IExporterHeaderFilter exporterHeader
/// <returns>文件</returns>
public virtual ExcelPackage Export(ICollection<T> dataItems)
{
ParseData(dataItems);
AddDataItems(dataItems);
if (!IsExpandoObjectType)
{
var list = ParseData(dataItems);
AddDataItems(list);
}
else
{
AddDataItems(dataItems);
}
// 为了传入dataItems,在这里提前调用一下
if (_exporterHeaderList == null) GetExporterHeaderInfoList(null, dataItems);
//仅当存在图片表头才渲染图片
Expand Down Expand Up @@ -496,7 +499,7 @@ public ExcelWorksheet AddExcelWorksheet(string name = null)
/// </summary>
/// <param name="dataItems"></param>
/// <param name="excelRange"></param>
protected void AddDataItems(ICollection<T> dataItems, ExcelRangeBase excelRange = null)
protected void AddDataItems(dynamic dataItems, ExcelRangeBase excelRange = null)
{
if (excelRange == null)
excelRange = CurrentExcelWorksheet.Cells["A1"];
Expand All @@ -509,51 +512,81 @@ protected void AddDataItems(ICollection<T> dataItems, ExcelRangeBase excelRange
var tbStyle = TableStyles.Medium10;
if (!ExcelExporterSettings.TableStyle.IsNullOrWhiteSpace())
tbStyle = (TableStyles)Enum.Parse(typeof(TableStyles), ExcelExporterSettings.TableStyle);
var er = IsExpandoObjectType
? excelRange.LoadFromDictionaries(dataItems as List<ExpandoObject>, true, TableStyles.None)
: excelRange.LoadFromCollection(dataItems, true, TableStyles.None);
var er = excelRange.LoadFromDictionaries(dataItems, true, TableStyles.None);
CurrentExcelTable = CurrentExcelWorksheet.Tables.GetFromRange(er);
}
else
{
if (IsExpandoObjectType)
excelRange.LoadFromDictionaries(dataItems as List<ExpandoObject>, true, TableStyles.None);
excelRange.LoadFromDictionaries(dataItems, true, TableStyles.None);
else
excelRange.LoadFromCollection(dataItems, true, TableStyles.None);
excelRange.LoadFromDictionaries(dataItems, true, TableStyles.None);
}
}

/// <summary>
/// 数据解析
/// </summary>
/// <param name="dataItems"></param>
protected virtual void ParseData(ICollection<T> dataItems)
protected virtual List<ExpandoObject> ParseData(ICollection<T> dataItems)
{
var type = typeof(T);
var properties = type.GetProperties();
List<ExpandoObject> list = new List<ExpandoObject>();
foreach (var dataItem in dataItems)
{
//var data = new T();
dynamic obj = new ExpandoObject();
foreach (var propertyInfo in properties)
{
if (propertyInfo.PropertyType.IsEnum)
{

var col = ExporterHeaderList.First(a => a.PropertyName == propertyInfo.Name);
var value = type.GetProperty(propertyInfo.Name)?.GetValue(dataItem);
//if (col.MappingValues.Count>0&& col.MappingValues.ContainsKey(dataItem))
//{

//}
propertyInfo.SetValue(dataItem,
10);
}

}
var value = type.GetProperty(propertyInfo.Name)?.GetValue(dataItem)?.ToString();

}
if (col.MappingValues.Count > 0 && col.MappingValues.ContainsKey(value ?? string.Empty))
{
var mapValue = col.MappingValues.FirstOrDefault(f => f.Key == value);
((IDictionary<string, object>)obj)[propertyInfo.Name] = mapValue.Value;
}
}
else if (propertyInfo.PropertyType.GetCSharpTypeName() == "Boolean")
{
var col = ExporterHeaderList.First(a => a.PropertyName == propertyInfo.Name);
var value = Convert.ToBoolean(type.GetProperty(propertyInfo.Name)?.GetValue(dataItem));

if (col.MappingValues.Count > 0 && col.MappingValues.ContainsKey(value))
{
var mapValue = col.MappingValues.FirstOrDefault(f => f.Key == value);
((IDictionary<string, object>)obj)[propertyInfo.Name] = mapValue.Value;
}
else
{
((IDictionary<string, object>)obj)[propertyInfo.Name] = value;
}
}
else if (propertyInfo.PropertyType.GetCSharpTypeName() == "Nullable<Boolean>")
{
var col = ExporterHeaderList.First(a => a.PropertyName == propertyInfo.Name);
var value = Convert.ToBoolean(type.GetProperty(propertyInfo.Name)?.GetValue(dataItem));

if (col.MappingValues.Count > 0 && col.MappingValues.ContainsKey(value))
{
var mapValue = col.MappingValues.FirstOrDefault(f => f.Key == value);
((IDictionary<string, object>)obj)[propertyInfo.Name] = mapValue.Value;
}
else
{
((IDictionary<string, object>)obj)[propertyInfo.Name] = value;
}
}
else
{
((IDictionary<string, object>)obj)[propertyInfo.Name] = type.GetProperty(propertyInfo.Name)?.GetValue(dataItem)?.ToString();
}
}
list.Add(obj);
}
return list;
}

/// <summary>
Expand Down Expand Up @@ -751,5 +784,6 @@ protected virtual void AddStyle()

}
}

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -864,7 +864,7 @@ protected virtual void ParseData(ExcelPackage excelPackage)
? rowIndex - 2 + (imageBaseIndex++ * worksheet.Dimension.End.Row)
: rowIndex - 3 + (imageBaseIndex++ * worksheet.Dimension.End.Row);
var excelPicture = GetImage(worksheet, position);
var path = Path.Combine(col.ImportImageFieldAttribute.ImageDirectory, Guid.NewGuid().ToString() + "." + excelPicture.ImageFormat.ToString());
var path = Path.Combine(col.ImportImageFieldAttribute.ImageDirectory, Guid.NewGuid() + "." + excelPicture.ImageFormat);
var value = string.Empty;

switch (col.ImportImageFieldAttribute.ImportImageTo)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -891,12 +891,13 @@ public async Task ExportTestDataAnnotations_Test()
sheet.Cells["C2"].Text.Equals(DateTime.Parse(sheet.Cells["C2"].Text).ToString("yyyy-MM-dd"));

sheet.Cells["D2"].Text.Equals(DateTime.Parse(sheet.Cells["D2"].Text).ToString("yyyy-MM-dd"));
new List<string> {"是", "否"}.ShouldContain(sheet.Cells["G2"].Text);
sheet.Tables.Count.ShouldBe(1);
var tb = sheet.Tables.First();

tb.Columns[0].Name.ShouldBe("Custom列1");
tb.Columns[1].Name.ShouldBe("列2");
tb.Columns.Count.ShouldBe(4);
tb.Columns.Count.ShouldBe(8);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,16 @@ public class ExportTestDataAnnotations

[ValueMapping("A Test", "A")]
[ValueMapping("B Test", "B")]
public MyEmum Testa { get; set; }
public MyEmum MyEmum { get; set; }

[ValueMapping("是", true)]
[ValueMapping("否", false)]
public bool? Bool { get; set; }

[ValueMapping("是", true)]
[ValueMapping("否", false)]
public bool Bool1 { get; set; }
public bool Bool2 { get; set; }
}

public enum MyEmum
Expand Down

0 comments on commit d910c82

Please sign in to comment.