前端实现导出excel

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

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

对应的service层(internalService):

public void batchTransformInternalFeedback(String title, List itemList, HttpServletResponse response) {
        if (CollectionsUtil.isEmpty(itemList)){
            return  null;
        }
        log.info("info detail {}", JSON.toJSONArray(itemList));
        List exports = new ArrayList<>();
        try {
            //构建表头
            itemList.stream().forEach(s->{
                ExportInternalFeeback feedback = new ExportInternalFeeback();
                ItemVO itemVO = s.getFeedbackBDO();
                BeanUtils.copyProperties(itemVO, feedback);
                exports.add(feedback);
            });
            Class 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)
    });
}

你可能感兴趣的:(前端,前端,excel)