JAVA-导出EXCEL并加密文件

springboot 2.0.72.0.7.RELEASE
jdk 1.8
poi 3.17

		<dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.17</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17</version>
        </dependency>

将workBook 写入到 ByteArrayOutputStream
并通过try-with-resources 结构进行自动资源管理,可以自动关闭对应的操作。

一定要是 XSSFWorkbook 2007之后的
并且一定要先生成本地文件 再对该文件进行加密

public void exportCardPwd(String orderNo, HttpServletResponse response) throws IOException, GeneralSecurityException, InvalidFormatException {
        List<OrderWithMsgCodeExcelDTO> orderList = orderService.listToExcelWithMsgCode(orderNo);
        String phone;
        if (CollectionUtils.isEmpty(orderList)) {
            throw new IllegalArgumentException("无数据");
        } else {
            phone = orderList.get(0).getPhone();
        }
        if (StringUtils.isEmpty(phone)) {
            throw new IllegalArgumentException("无法获取手机号");
        }

        ExcelUtil<OrderWithMsgCodeExcelDTO> excelUtil = new ExcelUtil<>(OrderWithMsgCodeExcelDTO.class);
        try (ByteArrayOutputStream baops = excelUtil.exportExcel2007(orderList, "订单记录")) {
            // 生成对应的临时文件
            long l = System.currentTimeMillis();
            String filename = localPath + "order" + l + ".xlsx";
            // 生成随机密码
            String password = RandomStringUtils.random(8, true, true).toUpperCase(Locale.ROOT);
            try (InputStream inputStream = new ByteArrayInputStream(baops.toByteArray());
                 POIFSFileSystem fs = new POIFSFileSystem()) {
                //设置加密信息并加密文件
                EncryptionInfo info = new EncryptionInfo(EncryptionMode.standard);
                Encryptor enc = info.getEncryptor();
                enc.confirmPassword(password);
                OPCPackage opc = OPCPackage.open(inputStream);
                OutputStream os = enc.getDataStream(fs);
                opc.save(os); // 加密文件
                opc.close();
                //把加密后的文件写回到流
                try (FileOutputStream fos = new FileOutputStream(filename)) {
                    fs.writeFilesystem(fos);
                }
                //向 response 输出文件
                response.reset();
                response.setContentType("application/octet-stream");
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("订单记录.xlsx", "UTF-8"));
                try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filename));
                     BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream())) {
                    byte[] buff = new byte[1024];
                    int bytesRead;
                    while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                        bos.write(buff, 0, bytesRead);
                    }
                    bos.flush();
                }

                // 发送短信并删除临时文件
                sendSms(phone, password);
                File file = new File(filename);
                if (file.exists() && file.delete()) {
                    log.info("File deleted successfully: {}", filename);
                } else {
                    log.error("Failed to delete the file: {}", filename);
                }
            } catch (IOException | GeneralSecurityException | InvalidFormatException e) {
                log.error("Failed to export file, error: {}", e.getMessage());
                throw e;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值