自定义导出字段导出excel

后端

@PostMapping("/export")
public void exportData(@ApiIgnore @RequestBody Map<String, Object> formData, HttpServletRequest request, HttpServletResponse response) throws IOException, DownloadException {
    ArrayList<LinkedHashMap<String, Object>> exportFiled = new ArrayList<>();
    if (formData.containsKey("exportFiled")) {
        exportFiled = (ArrayList) formData.get("exportFiled");
        formData.remove("exportFiled");
    }
    if (exportFiled.size() == 0) {
        throw new DownloadException("最少选择一项导出字段");
    }

    List<RecordingBillEntity> list = service.queryList(formData);


    HSSFWorkbook workbook = new HSSFWorkbook();

    Sheet sheet = workbook.createSheet("123");

    int rowIndex = 0;

    //region 列名
    Row headerRow = sheet.createRow(rowIndex);   //第一行,列头

    CellStyle headStyle = workbook.createCellStyle();   //列头样式设置
    headStyle.setAlignment(HorizontalAlignment.CENTER);
    headStyle.setVerticalAlignment(VerticalAlignment.CENTER);

    Font font = workbook.createFont();
    font.setFontHeightInPoints((short) 12);
    font.setBold(true);
    headStyle.setFont(font);

    int i = 0;
    headerRow.createCell(i).setCellValue("序号");
    headerRow.getCell(i).setCellStyle(headStyle);
    sheet.setColumnWidth(i, 5 * 256);
    i++;

    for (LinkedHashMap<String, Object> filed : exportFiled) {

        headerRow.createCell(i).setCellValue(MapUtils.getString(filed, "name"));
        headerRow.getCell(i).setCellStyle(headStyle);
        sheet.setColumnWidth(i, 18 * 256);

        i++;
    }

    rowIndex++;
    //endregion

    //region 数据
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    for (RecordingBillEntity entity : list) {

        CellStyle itemStyle = workbook.createCellStyle();
        itemStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        itemStyle.setAlignment(HorizontalAlignment.LEFT);

        Row itemRow = sheet.createRow(rowIndex);
        itemRow.setHeightInPoints(25);

        int ci = 0;
        itemRow.createCell(ci).setCellValue(rowIndex + 1);
        itemRow.getCell(ci).setCellStyle(itemStyle);
        ci++;

        for (LinkedHashMap<String, Object> filed : exportFiled) {

            String filedCode = MapUtils.getString(filed, "value");

            Cell cell = itemRow.createCell(ci);
            cell.setCellStyle(itemStyle);
            String v = "";

            try {
                Field f = entity.getClass().getDeclaredField(filedCode);
                f.setAccessible(true);
                Object value = f.get(entity);

                if (f.getType().equals(Date.class)) {
                    v = sdf.format((Date) value);
                } else {
                    v = String.valueOf(value);
                }

                ci++;
            } catch (NoSuchFieldException | IllegalAccessException e) {
                e.printStackTrace();
            }

            cell.setCellValue(v);
        }


        rowIndex++;
    }

    //endregion


    //region export

    response.reset();
    response.setCharacterEncoding("UTF-8");
    response.setContentType("application/ms-word");
    //  response.setContentLength(att.getSize());

    String filename = "123.xls";
    //设置文件下载头
    String agent = (String) request.getHeader("USER-AGENT");
    if (agent != null && agent.indexOf("Firefox") != -1) {
        String enableFileName = "=?UTF-8?B?" + (new String(Base64.encodeBase64(filename.getBytes("UTF-8")))) + "?=";
        response.setHeader("Content-Disposition", "attachment; filename=" + enableFileName);
    } else {
        //转码,免得文件名中文乱码
        filename = URLEncoder.encode(filename, "UTF-8");
        response.addHeader("Content-Disposition", "attachment;filename=" + filename);
    }

    response.addHeader("Last-Modified", new Date().toString());
    // response.addHeader("Content-Length", att.getSize() + "");

    @Cleanup OutputStream os = response.getOutputStream();
    workbook.write(os);
    response.flushBuffer();

    //endregion
}

 前端调用

that.$http({
        method: 'post',
        url: "/export",
        data: params,
        responseType: 'blob',//服务器返回的数据类型
    }).then((res) => {
        // 处理返回的文件流

        const blob = new Blob([res.data],{type: "application/vnd.ms-excel"});//,{type: 'application/vnd.ms-excel;charset=utf-8'}

        let fileName = '123.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); // 释放URL 对象

        document.body.removeChild(elink);

    }).catch(err => {
        console.log(err);
    })
},

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值