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();
        }
    }
Java可以使用Apache POI库来对生成的Excel进行加密。下面是一个简单的示例: ```java import java.io.FileOutputStream; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.poifs.crypt.EncryptionInfo; import org.apache.poi.poifs.crypt.Encryptor; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcelEncryptionExample { public static void main(String[] args) throws Exception { // 创建一个新的Excel工作簿 XSSFWorkbook workbook = new XSSFWorkbook(); // 向工作簿中添加一些数据和格式化 // 创建一个加密信息对象 EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile); // 创建一个加密器对象 Encryptor enc = info.getEncryptor(); // 设置加密密码 enc.confirmPassword("password"); // 创建一个输出流 FileOutputStream fos = new FileOutputStream("encrypted.xlsx"); // 使用加密器将工作簿写入输出流 workbook.write(enc.getDataStream(fos)); // 关闭输出流和工作簿 fos.close(); workbook.close(); } } ``` 在上面的示例中,我们创建了一个新的Excel工作簿,并使用EncryptionInfo和Encryptor对象将其加密。在这个例子中,我们使用了一种名为“agile”的加密模式,但是POI库支持多种加密模式。请注意,在设置密码时,我们使用了enc.confirmPassword("password")方法来设置加密密码。 最后,我们将加密后的工作簿写入一个输出流,并关闭输出流和工作簿。现在,生成的Excel文件将受到密码保护,只有知道密码的人才能打开和编辑文件
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值