ABP框架使用总结之使用Axios来导出Excel

需求说明

点击按钮,获取页面form表单的数据,发送到服务器生成Excel文档并下载到客户端。

如果参数比较简单,我们可以直接通过GET请求访问生成Excel文档的Action。如:

location.href = abp.appPath + 'Service/Export?input=' + result;

但是,如果参数比较复杂,且数量较多,继续使用这种方式则显得比较繁琐,并且容易报错。
此时,我们可以迂回一下,先把请求参数缓存到服务器,然后在生成Excel时从缓存获取参数。

以下是具体的实现:

前台页面中导出按钮的点击事件代码如下:

//先请求SaveData接口来缓存参数,然后用返回的result作为参数访问Export来导出Excel文档
_this.genDatas(function (result) {
       //result 生成的表单数据
       axios.post(abp.appPath + 'Service/SaveData', result).then(function (result) {
              _this.matloading = false;
              location.href = abp.appPath + 'Service/Export?input=' + result;
       });
});

Controller 代码:

public class ServiceController : ControllerBase
    {
        protected readonly IServiceAppService _serviceAppService;
        private readonly ICacheManager _cacheManager;
        public SendServiceController(IServiceAppService serviceAppService, ICacheManager cacheManager)
        {
            _cacheManager = cacheManager;
            _serviceAppService = serviceAppService;
        }
        /// <summary>
        /// 缓存参数,并返回No
        /// </summary>
        [System.Web.Http.HttpPost]
        public JsonResult SaveData(InputDto input)
        {
            AsyncHelper.RunSync(()=>_cacheManager.GetCache("Export").SetAsync(input.No, input, TimeSpan.FromMinutes(10)));
            return Json(input.No, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 导出Excel
        /// </summary>
        public FileResult Export(string input)
        {
            try
            {
                var items = _cacheManager.GetCache("Export").GetOrDefault<string, InputDto>(input);
                var model = _serviceAppService.GetExportInfo(items);
                HSSFWorkbook workbook = new HSSFWorkbook();
                BuildExcel(workbook.CreateSheet("物品汇总列表"), model.Details.ToArray());
                Stream ms = new MemoryStream();
                workbook.Write(ms);
                ms.Seek(0, SeekOrigin.Begin);
                return File(ms, "application/ms-excel", "物品列表.xls");
            }
            catch (Exception ex)
            {
                throw new Exception("生成Excel出错", ex);
            }

        }
        /// <summary>
        /// 生成Excel 只生成带有[DisplayName]特性的字段
        /// </summary>
        public void BuildExcel<T>(ISheet sheet,T[] list) where T : new()
        {
            var properties = typeof(T).GetProperties();
            for (int num = 0; num <= list.Length; num++)
            {
                var model = num == 0 ? new T() : list[num - 1];
                IRow row = sheet.CreateRow(num);
                var cellCol = 0;
                for (int index = 0; index < properties.Length; index++)
                {
                    var property = properties[index];
                    var attr = property.GetCustomAttribute<DisplayNameAttribute>();
                    if (attr == null)
                        continue;
                    if (num == 0)
                    {
                        row.CreateCell(cellCol).SetCellValue(attr.DisplayName);
                        cellCol++;
                        continue;
                    }
                    var value = property.GetValue(model, null) ?? "";
                    switch (property.PropertyType.ToString())
                    {
                        case "System.Boolean":
                            row.CreateCell(cellCol).SetCellValue(Convert.ToBoolean(value));
                            break;
                        case "System.DateTime":
                            row.CreateCell(cellCol).SetCellValue(Convert.ToDateTime(value).ToString("yyyy-MM-dd hh:mm:ss"));
                            break;
                        case "System.Double":
                        case "System.Int32":
                        case "System.Decimal":
                            row.CreateCell(cellCol).SetCellValue(Convert.ToDouble(value));
                            break;
                        default:
                            row.CreateCell(cellCol).SetCellValue(value.ToString());
                            break;
                    }
                    cellCol++;
                }
            }
        }  
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容