首先,做到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)
    });
}
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐