我希望使用apache保护带有密码的.doc文件。在运行代码时,我会得到这个错误。请帮帮我
线程“主”org.apache.poi.openxml4j.exceptions.OLE2NotOfficeXmlFileException:中的异常所提供的数据似乎是OLE2格式的。您正在调用POI中处理OOXML (Office )文档的部分。您需要在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)上调用POI的不同部分来处理这些数据(例如HSSF而不是XSSF)。在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");发布于 2018-06-29 16:38:32
我检查并引用了Apache 文档,它说.doc文件自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();
}
}或者您可以签出完整的代码这里:
如果您有进一步的问题或反馈,请告诉我。谢谢
https://stackoverflow.com/questions/50949352
复制相似问题