1. 程式人生 > 實用技巧 >C# 匯出表格時表頭優化思路

C# 匯出表格時表頭優化思路

眾所周知

眾所周知,如果使用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表示還需要再次做反射嘗試。