POI 加密Excel文件

今天遇到一个业务,需要为Excel 文件加密后发送邮件给客户,Excel文件需要使用密码才能打开。

在网上查了一轮后发现官网有相应的例子可以参考,可以看官网资料(参考http://poi.apache.org/encryption.html)。

下面的例子只能支持Excel 2007文件

        //Add password protection and encrypt the file
        final POIFSFileSystem fs = new POIFSFileSystem();
        final EncryptionInfo info = new EncryptionInfo(EncryptionMode.standard);
        //final EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile, CipherAlgorithm.aes256, HashAlgorithm.sha256, -1, -1, null);
        final Encryptor enc = info.getEncryptor();

        //set the password
        enc.confirmPassword("abcdef");

        //encrypt the file
        final OPCPackage opc = OPCPackage.open(new File(path), PackageAccess.READ_WRITE);
        final OutputStream os = enc.getDataStream(fs);
        opc.save(os);
        opc.close();

        //save the file back to the filesystem
        final FileOutputStream fos = new FileOutputStream(path);
        fs.writeFilesystem(fos);
        fos.close();

  这里可选的EncryptionMode有多种,本人简单测试,只有EncryptionMode.standard、EncryptionMode.binaryRC4可以不需要其它参数就加密成功。

用EncryptionMode.agile 加密则打开Excel 文件还是有问题(可以不输入密码打开文件,文件无内容)。而官网写着binaryRC4是不安全。需要继续看文档或者研究才能断续。

原文地址:https://www.cnblogs.com/latteyan/p/6165983.html