C#導出Excel-利用特性自定義數據


 網上C#導出Excel的方法有很多。但用來用去感覺不夠自動化。於是花了點時間,利用特性做了個比較通用的導出方法。只需要根據實體類,自動導出想要的數據

 

 1.在NuGet上安裝Aspose.Cells或者用微軟自帶類庫也可以

 2.需要導出的數據的實例類:

 using System.ComponentModel;
    using System.Reflection;
    using System.Runtime.Serialization;
    public class OrderReport
    {
        [DisplayName("訂單編號")]
        public string orderNo { get; set; }

        [IgnoreDataMember]
        public DateTime orderTime { get; set; }
        [DisplayName("訂單時間")]
        public String orderTime_fomart { get { return orderTime.ToShortDateString(); } }

        [DisplayName("商品編碼")]
        public string itemCode { get; set; }

        [DisplayName("商品名稱")]
        public string itemName { get; set; }
    }
View Code
定義實體中加上 [DisplayName("訂單編號")]用來導出到Excel生成列名。不需在導出一一對應寫列名。[IgnoreDataMember]屬性是用來導出是忽略掉不用導出 。
關於特性的介紹詳細請參考MSDN。

3.實現導出方法:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using Aspose.Cells;

/// <summary>
/// 導出類
/// </summary>
public class ExcelHerper
{
    /// <summary>
    /// 獲取定義的特性值
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="provider"></param>
    /// <returns></returns>
    public static T GetAttribute<T>(ICustomAttributeProvider provider)
    where T : Attribute
    {
        return provider.GetCustomAttributes(typeof(T), true)
            .Cast<T>().ToArray().FirstOrDefault();
    }

    /// <summary>
    ///訂單報表導出
    /// </summary>
    public static void ExecExportOrderReport()
    {
        var orderReportList = new List<OrderReport>()
            {
               new OrderReport() { orderNo= "XD00001",orderTime=DateTime.Now, itemCode="G001" ,itemName="辣條"} ,
               new OrderReport() { orderNo= "XD00002", orderTime=DateTime.Now,itemCode="G002" ,itemName="茶蛋"} ,
               new OrderReport() { orderNo= "XD00003", orderTime=DateTime.Now,itemCode="G003" ,itemName="切糕"} ,
               new OrderReport() { orderNo= "XD00004", orderTime=DateTime.Now,itemCode="G004" ,itemName="大蝦"} ,
               new OrderReport() { orderNo= "XD00005", orderTime=DateTime.Now,itemCode="G005" ,itemName="帝王蟹"}
            };
        string path = "OrderReport.xlsx";
        Console.WriteLine("開始執行導出");
        OutDataToExcel(orderReportList, path);
        Console.WriteLine("導出完成:位置" + path);
    }

    /// <summary>
    /// 導出方法
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="list">導出的數據list</param>
    /// <param name="title">數據類容標題</param>
    /// <param name="path">導出excel存放路徑</param>
    public static void OutDataToExcel<T>(List<T> list,string path)
    {
        Workbook workbook = new Workbook(); //工作簿 
        Worksheet sheet = workbook.Worksheets[0]; //工作表 
        sheet.IsGridlinesVisible = false;//去掉初始單元線
        Cells cells = sheet.Cells;//單元格 
                                  //為標題設置樣式     
        Style styleTitle = workbook.CreateStyle();//新增樣式 
        styleTitle.HorizontalAlignment = TextAlignmentType.Center;//文字居中 
        styleTitle.Font.Name = "微軟雅黑";//文字字體 
        styleTitle.Font.Size = 18;//文字大小 
        styleTitle.Font.IsBold = true;//粗體 
                                      //樣式1 標題下方的日期
        Style style1 = workbook.CreateStyle();//新增樣式 
        style1.HorizontalAlignment = TextAlignmentType.Center;//文字居中 
        style1.Font.Name = "微軟雅黑";//文字字體 
        style1.Font.Size = 12;//文字大小 
                              //樣式2 列名
        Style style2 = workbook.CreateStyle();//新增樣式 
        style2.HorizontalAlignment = TextAlignmentType.Center;//文字居中 
        style2.Font.Name = "微軟雅黑";//文字字體 
        style2.Font.Size = 12;//文字大小 
        style2.Font.IsBold = true;//粗體 
        style2.Borders[BorderType.LeftBorder].LineStyle = CellBorderType.Thin;
        style2.Borders[BorderType.RightBorder].LineStyle = CellBorderType.Thin;
        style2.Borders[BorderType.TopBorder].LineStyle = CellBorderType.Thin;
        style2.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin;
        //樣式3 數據的樣式
        Style style3 = workbook.CreateStyle();//新增樣式 
        style3.HorizontalAlignment = TextAlignmentType.Center;//文字居中 
        style3.Font.Name = "微軟雅黑";//文字字體 
        style3.Font.Size = 10;//文字大小 
        style3.Borders[BorderType.LeftBorder].LineStyle = CellBorderType.Thin;
        style3.Borders[BorderType.RightBorder].LineStyle = CellBorderType.Thin;
        style3.Borders[BorderType.TopBorder].LineStyle = CellBorderType.Thin;
        style3.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin;

        if (list.Count == 0) return;

        var t = list.First().GetType();//獲取列表的類的屬性
        var properties = t.GetProperties().Where(x => GetAttribute<IgnoreDataMemberAttribute>(x) == null);//篩選出需要導出的字段
        var title = GetAttribute<DisplayNameAttribute>(t)?.DisplayName;
        int Colnum = properties.Count();//表格列數 
        int Rownum = list.Count;//表格行數 

        //生成行1 標題行    
        cells.Merge(0, 0, 1, Colnum);//合並單元格 
        cells[0, 0].PutValue(title);//填寫內容 
        cells[0, 0].SetStyle(styleTitle);
        cells.SetRowHeight(0, 38);//行高
                                  //生成行2 日期    
        cells.Merge(1, 0, 1, Colnum);//合並單元格 
        cells[1, 0].PutValue(DateTime.Now.ToShortDateString());//填寫內容 
        cells[1, 0].SetStyle(style1);
        cells.SetRowHeight(1, 20);//行高
                                  //列名及數據行
        int i = 0;
        foreach (var item in properties)
        {
            var colName = GetAttribute<DisplayNameAttribute>(item)?.DisplayName;//反射獲取字段的DisplayName特性值
            cells[2, i].PutValue(colName);
            cells[2, i].SetStyle(style2);
            cells.SetColumnWidth(i, colName.Length * 3);//設置列寬
            int k = 0;
            foreach (var rowdata in list)
            {
                //反射遍歷添加數據
                object value = item.GetValue(rowdata, null);
                string ss = value == null ? "" : value.ToString();
                cells[3 + k, i].PutValue(ss);
                cells[3 + k, i].SetStyle(style3);
                cells.SetRowHeight(3 + k, 18);//設置行高
                k++;
            }
            i++;
        }
        workbook.Save(path);//生成Excel
    }
}


[DisplayName("訂單報表")]
public class OrderReport
{
    [DisplayName("訂單編號")]
    public string orderNo { get; set; }

    [IgnoreDataMember]
    public DateTime orderTime { get; set; }
    [DisplayName("訂單時間")]
    public string orderTime_fomart { get { return orderTime.ToShortDateString(); } }

    [DisplayName("商品編碼")]
    public string itemCode { get; set; }

    [DisplayName("商品名稱")]
    public string itemName { get; set; }
}
View Code

 

導出方法 OutDataToExcel<T>(List<T> list, Enum en, string path)用了泛型參數,將任意的實體list自動導出。 
var properties = t.GetProperties().Where(x => AttributeAccessor.GetAttribute<IgnoreDataMemberAttribute>(x) == null);采用lamda表達式在傳過來的實體屬性中篩選出
不是IgnoreDataMemberAttribute的屬性字段

foreach (var item in properties){}遍歷實體類的屬性相當於DataTable循環讀取數據 

object value = rowdata.GetType().GetProperty(item.Name).GetValue(rowdata, null); 通過屬性名稱獲取屬性值。

通過以上兩個步驟,實現自動

 

 

}

4.導出結果:

總結,通過特性來實現通用的導出。只需要設置相關的類的字段和特性值即可自定義導出


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM