眾所周知
眾所周知,如果使用DataTable。一般的思路是這么寫的
var exprotData = new DataTable("Datas"); exprotData.Columns.Add("編號", Type.GetType("System.String")); exprotData.Columns.Add("交易號", Type.GetType("System.String"));
然后數據組裝,需要
dr["編號"] = item.Id; dr["交易號"] = item.TransNumber;
這樣倒是沒有啥毛病,但一來二去修改字段要去修改多處代碼。多的話可能會漏掉
優化思路
這里沒有經過嚴格的測試。只是進行嘗試
自己寫一個Attribute(或者用現成的displayName)
public class DataGridPropertyAttribute : Attribute { public string Name { get; set; } public bool IsHaveChild { get; set; } /// <summary> /// 標記導出到表格的屬性 /// </summary> /// <param name="name">列表頭</param> /// <param name="isHaveChild">是否含有二級數據</param> public DataGridPropertyAttribute(string name,bool isHaveChild = false) { Name = name; IsHaveChild = isHaveChild; } }
然后寫一個擴展方法。把標記號的全部用dictionary保存
public static class CustomAttributeExtensions { public static Dictionary<DataGridPropertyAttribute, object> GetCustomAttributeEntity<TEntity>(this TEntity entity) where TEntity : class { var dic = new Dictionary<DataGridPropertyAttribute, object>(); var type = entity.GetType(); var propInfos = type.GetProperties(); foreach (var propertyInfo in propInfos) { if (!propertyInfo.IsDefined(typeof(DataGridPropertyAttribute), false)) continue; DataGridPropertyAttribute attribute = (DataGridPropertyAttribute)propertyInfo.GetCustomAttribute(typeof(DataGridPropertyAttribute), false); var name = attribute.Name; if(string.IsNullOrEmpty(name)) continue; if(dic.ContainsKey(attribute)) continue; var value = propertyInfo.GetValue(entity); dic.Add(attribute,value); } return dic; } }
為什么設定一個 isHaveChild
因為有些數據可能是無限套娃的。比如數據其實存在於OrderMallInfo里面,需要導出為店鋪名稱。標記為true以便於遞歸下去找到應該導出的字段(如果有更好的方法請評論告訴我~~)
[DataGridProperty("店鋪",true)] [JsonProperty("mall_info")] public OrderMallInfo OrderMallInfo { get; set; }
public class OrderMallInfo { [DataGridProperty("店鋪名稱")] [JsonProperty("platform_mall_name")] public string PlatformMallName { get; set; } }
實際運行
false表示已經到尾。這個值需要作為列名,true表示還需要再次做反射嘗試。