美文网首页
poi导出excel设置密码 加密

poi导出excel设置密码 加密

作者: X作业写完了吗 | 来源:发表于2020-09-25 11:09 被阅读0次

最近有需求要做excel加密,实现方式是设置密码。
看代码:

public static void setPassword4OOXML(InputStream inputStream, OutputStream outputStream, String password)  {
        try (POIFSFileSystem fs = new POIFSFileSystem()) {
            EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile);
            Encryptor enc = info.getEncryptor();
            enc.confirmPassword(password);
            try (OPCPackage opc = OPCPackage.open(inputStream);
                 OutputStream os = enc.getDataStream(fs)) {
                opc.save(os);
            }
            fs.writeFilesystem(outputStream);
        } catch (Exception e) {
            log.error("setPwd4OOXML ex : {}" ,e);
        }
    }
public static void setPassword4OfficeFile(String path, String password)  {
        try (POIFSFileSystem fs = new POIFSFileSystem()) {
            EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile);
            Encryptor enc = info.getEncryptor();
            enc.confirmPassword(password);
            try (OPCPackage opc = OPCPackage.open(new File(path), PackageAccess.READ_WRITE);
                 OutputStream os = enc.getDataStream(fs)) {
                opc.save(os);
            }
            try (FileOutputStream fos = new FileOutputStream(path)) {
                fs.writeFilesystem(fos);
            }
        } catch (Exception e) {
            log.error("setPwd office file ex : {}" ,e);
        }
    }

要啥自行车,代码请自行优化 TODO
参考:https://poi.apache.org/encryption.html

相关文章

网友评论

      本文标题:poi导出excel设置密码 加密

      本文链接:https://www.haomeiwen.com/subject/pjtfuktx.html