C# net core epplus 导出 Excel List转Excel


首先引入  epplus 

     public static void ForEach(this IEnumerable ts, Actionint> fn)
        {

            var arr = (IList)ts ?? ts.ToList();

            for (var i = 0; i < arr.Count(); i++)

                fn(arr[i], i);

        }
     /// 
        /// 数据转Xlsx
        /// 
        /// 
        /// 
        /// 要显示的列名及标题
        /// 
        public static FileContentResult ToExcelBinary(this IEnumerable ts, params Entity.ExcelColumn[] cols)
        {

            ExcelPackage.LicenseContext = LicenseContext.NonCommercial;

            var ep = new ExcelPackage();

            var props = typeof(T).GetProperties();

            var sheet = ep.Workbook.Worksheets.Add("Sheet1");

            cols.ForEach((o, i) =>
            {
                sheet.Row(1).Height = 24;
                sheet.Column(i + 1).Width = 20;
                sheet.Cells[1, i + 1].Value = o.Title ?? o.Name;
            });

            ts.ForEach((o, i) =>
            {

                cols.ForEach((x, j) =>
                {

                    sheet.Row(i + 2).Height = 24;

                    sheet.Cells[i + 2, j + 1].Value = props.SingleOrDefault(m => m.Name.ToLower() == x.Name.ToLower())?.GetValue(o) ?? "";

                });

            });

            return new FileContentResult(ep.GetAsByteArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

        }
public class ExcelColumn
    {
        /// 
        /// title:显示标题,name:字段名称
        /// 
        /// 字段名称
        /// 显示的标题
        public ExcelColumn(string title,string name) { 
            Name = name;
            Title = title;
        }
     /// 
        /// 字段名称
        /// 
        public string Name { get; set; }
        /// 
        /// 显示标题
        /// 
        public string Title { get; set; }
    
        public int Sort { get; set; }
}