Java autopoi 后台多sheet导出Excel、zip导出,简单笔记

只展示部分代码,其中用到的业务数据需要自行调整。

上代码

public VExportNew exportNew(XtdwwfDateParam params) {
        VExportNew resp = new VExportNew();
        String hyxtxh = params.getHyxtxh();
        String xtlb = params.getXtlb();
        String xtlbmc = baseMapper.gethyxtlbMc(xtlb);
        try{
            // 多个导出
            if(StringUtils.isEmpty(hyxtxh)){
                LambdaQueryWrapper<ThyxtCompany> queryWrapper = new LambdaQueryWrapper<ThyxtCompany>()
                        .eq(ThyxtCompany::getHyxtlb, xtlb)
                        .eq(ThyxtCompany::getHyxtjb, 1);

                List<ThyxtCompany> list = this.list(queryWrapper);
                // 创建临时文件夹
                File fileDir = new File(exportFileDir, DateTime.now().toDateStr());
                fileDir.mkdirs();

                resp.setFileName(xtlbmc+"_时间"+params.getStartTime().substring(0, 10)+"_"+params.getEndTime().substring(0, 10)+"_"+DateUtils.getCurrentTimestamp()+".zip");
                resp.setFileType("application/zip");
                // Step 1: 创建一个临时文件用于存储压缩包
                String excelFileName = new String((UUID.randomUUID().toString().replace("-","")+".zip").getBytes(), "utf-8");
                File zipFile = new File(fileDir, excelFileName);
                FileOutputStream fileOutputStream = new FileOutputStream(zipFile);
                ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream);

                for (ThyxtCompany it : list) {
                    this.installExport(it, zipOutputStream, params);
                }
                zipOutputStream.close();
                fileOutputStream.close();

                File file = new File(fileDir.getAbsolutePath()+ File.separator+excelFileName);
                FileInputStream fis = new FileInputStream(file);
                ByteArrayOutputStream baos = new ByteArrayOutputStream((int) file.length());
                byte[] buffer = new byte[1024];
                int length;
                while ((length = fis.read(buffer)) != -1) {
                    baos.write(buffer, 0, length);
                }
                fis.close();
                baos.close();
                resp.setFile(baos.toByteArray());
            }
            // 单个导出
            else{
                LambdaQueryWrapper<ThyxtCompany> queryWrapper = new LambdaQueryWrapper<ThyxtCompany>()
                        .eq(ThyxtCompany::getHyxtlb, xtlb)
                        .eq(ThyxtCompany::getXtxh, hyxtxh);
                ThyxtCompany one = this.getOne(queryWrapper);
                if(null != one){
                    Workbook oneWorkbook = this.installExport(one, null, params);
                    if(null != oneWorkbook){
                        resp.setFileName(one.getHyxtmc()+"_时间"+params.getStartTime().substring(0, 10)+"_"+params.getEndTime().substring(0, 10)+"_"+DateUtils.getCurrentTimestamp()+".xls");
                        resp.setFileType("application/vnd.ms-excel");
                        resp.setFile(workbookToByteArray(oneWorkbook));
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            resp = null;
        }
        return resp;
    }

    private Workbook installExport(ThyxtCompany it, ZipOutputStream zipOutputStream, XtdwwfDateParam params) {
        String exportType = params.getExportType();
        Workbook workbook = null;
        if(null == it  || null == exportType){
            return workbook;
        }

        String title = it.getHyxtmc();
        Date start = null;
        Date end = null;
        try {
            start = DateUtils.parseDate(params.getStartTime(), "yyyy-MM-dd HH:mm:ss");
            end = DateUtils.parseDate(params.getEndTime(), "yyyy-MM-dd HH:mm:ss");
            SimpleDateFormat sdf = DateUtils.date_sdf_wz.get();
            title+= sdf.format(start)+"~"+sdf.format(end);
        }catch (Exception e){
            e.printStackTrace();
        }

        List<VXtdwExport> xtdwExport = this.getXtdwExport(it.getHyxtlb(), it.getXtxh().toString(), params.getStartTime(), params.getEndTime());

        if(exportType.equals("1")){// 1 单个sheet 导出统计项
            try {
                ExportParams exportParams = new ExportParams( title, "统计");
                exportParams.setAddIndex(true); // 序号哦
                exportParams.setStyle(ExcelExportStylerBorderImpl.class);
                workbook = ExcelExportUtil.exportExcel(exportParams, VXtdwExport.class, xtdwExport);
                // Step 2: 添加Excel 文件到压缩包中
                if(null != zipOutputStream){
                    // 获取文件字节
                    byte[] bytes = workbookToByteArray(workbook);
                    addExcelToZip(zipOutputStream, it.getHyxtmc()+".xls", bytes);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        if(exportType.equals("2")){// 2 多个shee
            // 多个sheet页导出
            List<Map<String, Object>> list = new ArrayList<>();
            // sheet1 统计数据
            HashMap<String, Object> export1 = new HashMap<>();

            ExportParams exportParams1 = new ExportParams(it.getHyxtmc(), "单位统计");
            exportParams1.setAddIndex(true); // 序号哦
            exportParams1.setStyle(ExcelExportStylerBorderImpl.class);
            export1.put("title", exportParams1);
            export1.put("entity", VXtdwExport.class);
            export1.put("data", xtdwExport);
            list.add(export1);

            // 数据
            List<Map<String, Object>> maps = itBaseCompanyService.seleData(it.getHyxtjb(), it.getXtxh().toString(), params, "-1");
            Map<String, List<Map<String, Object>>> groupLists = maps.stream().collect(Collectors.groupingBy(map -> map.get("XXLY").toString().trim()));
            maps.clear();

            // sheet2 数据
            List<Map<String, Object>> xcwf = groupLists.containsKey("1") ? groupLists.get("1") : new ArrayList<>();
            ExportParams exportParams2 = new ExportParams(title, "数据");
            exportParams2.setAddIndex(true); // 序号哦
            exportParams2.setStyle(ExcelExportStylerBorderImpl.class);
            HashMap<String, Object> export2 = new HashMap<>();
            List<ExcelExportEntity> entity2 = new ArrayList<ExcelExportEntity>();
            entity2.add(new ExcelExportEntity("类别", "LBMC", 15));
            entity2.add(new ExcelExportEntity("一级名称", "MC1", 25));
            entity2.add(new ExcelExportEntity("二级名称", "MC2", 35));
            entity2.add(new ExcelExportEntity("三级名称", "MC3", 45));
            entity2.add(new ExcelExportEntity("四级名称", "MC4", 20));
            entity2.add(new ExcelExportEntity("五级名称", "MC5", 20));
            export2.put("title", exportParams2);
            export2.put("entity", entity2);
            export2.put("data", xcwf);
            list.add(export2);

            // sheet3 数据
            List<Map<String, Object>> fxcwf = groupLists.containsKey("2") ? groupLists.get("2") : new ArrayList<>();
            ExportParams exportParams3 = new ExportParams(title, "数据");
            exportParams3.setAddIndex(true); // 序号哦
            exportParams3.setStyle(ExcelExportStylerBorderImpl.class);
            HashMap<String, Object> export3 = new HashMap<>();
            export3.put("title", exportParams3);
            export3.put("entity", entity2);
            export3.put("data", fxcwf);
            list.add(export3);

            // sheet4 数据
            Page<VHyxtAcdVo> page = new Page<>(1,-1);
            VHyxtAcdVo vHyxtAcdVo = new VHyxtAcdVo();
            vHyxtAcdVo.setFlag("wrsg");
            vHyxtAcdVo.setStartTime(start);
            vHyxtAcdVo.setEndTime(end);
//            xztj
            vHyxtAcdVo.setXztj("hyxtbh_"+it.getHyxtjb());
            vHyxtAcdVo.setXtxh(it.getXtxh().toString());
            Page<VHyxtAcdVo> vHyxtAcdVoPage = vHyxtAcdVoService.wflqsPageList(page, vHyxtAcdVo);
            List<VHyxtAcdVo> wrsgList  = vHyxtAcdVoPage.getRecords();
            ExportParams exportParams4 = new ExportParams(title, "数据");
            HashMap<String, Object> export4 = new HashMap<>();
            export4.put("title", exportParams4);
            export4.put("entity", VHyxtAcdVo.class);
            export4.put("data", wrsgList);
            list.add(export4);

            try {
                // 组装获取excel
                workbook = this.exportExcel(list, ExcelType.HSSF);
                // Step 2: 添加Excel 文件到压缩包中
                if(null != zipOutputStream){
                    // 获取文件字节
                    byte[] bytes = workbookToByteArray(workbook);
                    // Step 2: 添加Excel 文件到压缩包中
                    addExcelToZip(zipOutputStream, it.getHyxtmc()+".xls", bytes);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        return workbook;
    }

    public  Workbook exportExcel(List<Map<String, Object>> list, ExcelType type) {
        Workbook workbook;
        if (ExcelType.HSSF.equals(type)) {
            workbook = new HSSFWorkbook();
        } else {
            workbook = new XSSFWorkbook();
        }
        for (Map<String, Object> map : list) {
            ExcelExportServer server = new ExcelExportServer();
            Object entity =  map.get("entity");
            if (entity instanceof List<?>) {
                server.createSheetForMap(workbook, (ExportParams) map.get("title"), (List<ExcelExportEntity>) map.get("entity"), (Collection) map.get("data"));
            }else{
                server.createSheet(workbook, (ExportParams) map.get("title"), (Class<?>) map.get("entity"), (Collection<?>) map.get("data"),null);
            }

        }
        return workbook;
    }


    private  byte[] workbookToByteArray(Workbook workbook) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            workbook.write(outputStream);
            return outputStream.toByteArray();
        } finally {
            outputStream.close();
        }
    }
    private void addExcelToZip(ZipOutputStream zipOutputStream, String filename, byte[] content) throws IOException {
        zipOutputStream.putNextEntry(new ZipEntry(filename));
        zipOutputStream.write(content);
        zipOutputStream.closeEntry();
    }

class

@Data
public class VExportNew {
    private String fileType;// 文件后缀 zip / xlsx / ...
    private String fileName;// 文件名
    private byte[] file;// ps.返回到前端已经是base64了
//    private String base64File;
}

前端

 const raw = window.atob(data.result.file);
        const byteNumbers = new Uint8Array(raw.length);
        for (let i = 0; i < raw.length; i++) {
          byteNumbers[i] = raw.charCodeAt(i);
        }
        let url = window.URL.createObjectURL(new Blob([byteNumbers], { type: data.result.fileType }))
        let link = document.createElement('a')
        link.style.display = 'none'
        link.href = url
        link.setAttribute('download', data.result.fileName)
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link) //下载完成移除元素
        window.URL.revokeObjectURL(url) //释放掉blob对象
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值