有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在java中使用Apache POI使用密码保护文档

我想保护一个孩子。使用ApachePOI的带有密码的文档文件。我在运行代码时遇到此错误。请帮帮我

Exception in thread "main" org.apache.poi.openxml4j.exceptions.OLE2NotOfficeXmlFileException: The supplied data appears to be in the OLE2 Format. You are calling the part of POI that deals with OOXML (Office Open XML) Documents. You need to call a different part of POI to process this data (eg HSSF instead of XSSF) at org.apache.poi.openxml4j.opc.internal.ZipHelper.verifyZipHeader(ZipHelper.java:179) at org.apache.poi.openxml4j.opc.internal.ZipHelper.openZipFile(ZipHelper.java:237) at org.apache.poi.openxml4j.opc.ZipPackage.(ZipPackage.java:134) at org.apache.poi.openxml4j.opc.ZipPackage.(ZipPackage.java:117) at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:257)

    POIFSFileSystem fs=new POIFSFileSystem();
    EncryptionInfo info=new EncryptionInfo(EncryptionMode.agile);
    Encryptor enc=info.getEncryptor();
    enc.confirmPassword("user");
    OPCPackage opc=OPCPackage.open("D:/Amar.doc", PackageAccess.READ_WRITE);
    OutputStream os=enc.getDataStream(fs);
    opc.save(os);
    opc.close();
    FileOutputStream stream=new FileOutputStream("D:/ao.doc");
    fs.writeFilesystem(stream);
    stream.close();
    System.out.println("running");

共 (1) 个答案

  1. # 1 楼答案

    我检查并参考了ApachePOIdocumentation,它说的是密码加密。从3.17版开始支持文档文件,所以我尝试一下

    它必须使用HWPFDocument来打开您的文档文件。 然后,您需要通过以下方式设置密码:

    Biff8EncryptionKey.setCurrentUserPassword(password);
    

    完整方法:

    public static void encryptDocFile(File inputDocFile, File outputDocFile, String password) {
        try {
            FileInputStream fileInput = new FileInputStream(inputDocFile);
            BufferedInputStream bufferInput = new BufferedInputStream(fileInput);
            POIFSFileSystem poiFileSystem = new POIFSFileSystem(bufferInput);
            // Setting password
            Biff8EncryptionKey.setCurrentUserPassword(password);
    
            HWPFDocument wordDoc = new HWPFDocument(poiFileSystem);
            FileOutputStream fileOut = new FileOutputStream(outputDocFile);
            wordDoc.write(fileOut);
            bufferInput.close();
            fileOut.close();
            wordDoc.close();
            System.out.println("Encrypted successfully");
        } catch (IOException e) {
            System.out.println("Failed to encrypt doc file");
            e.printStackTrace();
        }
    }
    

    或者您可以签出完整的代码here

    如果您有进一步的问题或反馈,请让我知道。多谢各位