前端实现导出excel

首先,做到excel导出需要后端支持输入流为二进制,作为post接口,可以返回二进制,也可以直接利用response的特性将结果塞进去,后端逻辑如下

@PostMapping(value = {"exportExcel"})
    public void exportExcel(@RequestBody Map<String,String> params, HttpServletResponse response) throws IOException {
        logger.info("exportExcel params={}", params.get("title"));
        response.setHeader("content-Type", "application/json");
        String title = params.get("title");
        List<AbirdCultureFeedbackVO> list = JSON.parseArray(params.get("data"), ItemVO.class);
        internalService.batchTransformInternalFeedback(title, list, response);
    }

对应的service层(internalService):

public void batchTransformInternalFeedback(String title, List<ItemVO> itemList, HttpServletResponse response) {
        if (CollectionsUtil.isEmpty(itemList)){
            return  null;
        }
        log.info("info detail {}", JSON.toJSONArray(itemList));
        List<ExportInternalFeeback> exports = new ArrayList<>();
        try {
            //构建表头
            itemList.stream().forEach(s->{
                ExportInternalFeeback feedback = new ExportInternalFeeback();
                ItemVO itemVO = s.getFeedbackBDO();
                BeanUtils.copyProperties(itemVO, feedback);
                exports.add(feedback);
            });
            Class<ExportInternalFeeback> aClass = ExportInternalFeeback.class;
            Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(null,title), aClass, exports);
            workbook.write(response.getOutputStream());
        }catch (IOException e){
            e.printStackTrace();
        }
    }

其次,前端传递选中的结果,传递给后端

const name = "***_" + new Date().getTime()
downloadFeedbackListApi(
  {title: name,
    data:JSON.stringify(selectedRows)}, name);
message.info("下载成功");

fetch接口,将拿到的二进制流,解析为Blob的格式

export function downloadFeedbackListApi(params, name) {
  return fetch(`/api/***`,
   {method: 'POST',
   headers: {
    'Content-Type': 'application/json;charset=UTF-8',
  },
   responseType:'blob',
   body:
   JSON.stringify(params)})
    .then(res => res.blob())     
    .then(data => {
      let blob = new Blob([data], {
        type: "application/vnd.ms-excel;charset=utf-8"
    });
      const fileName = `${name}.xls`
        const elink = document.createElement('a')
        elink.download = fileName
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href)
        document.body.removeChild(elink)
    });
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值