JAVA-导出EXCEL并加密文件

2023-12-13 18:33:53

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();
        }
    }

文章来源:https://blog.csdn.net/StrugglingXuYang/article/details/130963771
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。