EPPlus导出Excel表的通用模板函数

    public static class ExportToExcelHelper
    {
        /// <summary>
        /// 通用导出方法
        /// </summary>
        /// <typeparam name="T">导出类名</typeparam>
        /// <param name="data">导出数据集</param>
        /// <param name="headerPropertyMap">表头</param>
        /// <param name="sheetName">表名</param>
        /// <param name="dateFormat">日期格式化</param>
        /// <param name="customPropertyFunc">补充限制</param>
        /// <returns></returns>
        public static Stream ExportToExcel<T>(IEnumerable<T> data, Dictionary<string, string> headerPropertyMap, string sheetName, string dateFormat = "yyyy-mm-dd hh:mm:ss", Func<T, object> customPropertyFunc = null)
        {
            using (var package = new ExcelPackage())
            {
                var worksheet = package.Workbook.Worksheets.Add(sheetName);

                int columnIndex = 1;
                foreach (var headerPropertyPair in headerPropertyMap)
                {
                    worksheet.Cells[1, columnIndex].Value = headerPropertyPair.Key;
                    columnIndex++;
                }

                int row = 2;
                foreach (var item in data)
                {
                    columnIndex = 1;
                    foreach (var headerPropertyPair in headerPropertyMap)
                    {
                        var propertyName = headerPropertyPair.Value;
                        if (propertyName != null)
                        {
                            var property = item.GetType().GetProperty(propertyName);
                            if (property != null)
                            {
                                object value;
                                if (property.PropertyType == typeof(DateTime) || property.PropertyType == typeof(DateTime?))
                                {
                                 
                                    var time = (DateTime?)property.GetValue(item);
                                    if (time.HasValue)
                                    {
                                        value = time.Value;
                                        worksheet.Cells[row, columnIndex].Style.Numberformat.Format = dateFormat;
                                        
                                    }
                                    else
                                    {
                                        value = null;
                                    }
                                }
                                else if (property.PropertyType.IsEnum)
                                {
                                    var enumValue = property.GetValue(item);
                                    var enums = (Enum)Enum.Parse(property.PropertyType, enumValue.ToString());
                                    value = GetEnumDescription(enums);
                                    value = enumValue.ToString();

                                }

                                else
                                {
                                    value = property.GetValue(item);
                                }
                                if ( customPropertyFunc != null)
                                {
                                    value = customPropertyFunc(item);
                                }
                                worksheet.Cells[row, columnIndex].Value = value;
                            }
                        }
                        columnIndex++;
                    }
                    row++;
                }

                var stream = new MemoryStream();
                package.SaveAs(stream);
                stream.Position = 0;
                return stream;

           
            }
        }
        /// <summary>
        /// 获取枚举描述
        /// </summary>
        /// <param name="enumValue"></param>
        /// <returns></returns>
        public static string GetEnumDescription(Enum? enumValue)
        {
            string value = enumValue.ToString();
            FieldInfo field = enumValue.GetType().GetField(value);
            object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false);  //获取描述属性
            if (objs == null || objs.Length == 0)  //当描述属性没有时,直接返回名称
                return value;
            DescriptionAttribute descriptionAttribute = (DescriptionAttribute)objs[0];
            return descriptionAttribute.Description;
        }

    }

使用实例

        /// <summary>
        /// 导出设备基本信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> ExportDeviceBasicInfo(DeviceBasicInfo_QueryRequest query)
        {
            var result = await _deviceBasicInfoBLL.GetAllBasicDeviceInfo(query);
            var headerPropertyMap = new Dictionary<string, string>
            {

                { "设备编码", "Code" },
                { "设备型号", "Name" },
                { "IP地址", "IPAddress" },
                { "端口号", "Port" }
                
            };

            var fileType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            var stream = ExportToExcelHelper.ExportToExcel<DeviceBasicResponse>(result, headerPropertyMap, "设备基本信息表", "yyyy-mm-dd hh:mm:ss", null);

            return new FileStreamResult(stream, fileType)
            {
                FileDownloadName = "设备基本信息表.xlsx"
            };

        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ctgu20-律

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值