要使用Apache POI打开.docx文件并使用密码保存,您首先需要确保已经安装了Apache POI库
在项目的pom.xml文件中,添加以下依赖项:
<dependencies>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.xmlbeans</groupId>
<artifactId>xmlbeans</artifactId>
<version>5.1.1</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.4</version>
</dependency>
</dependencies>
import java.io.*;
import org.apache.poi.poifs.crypt.*;
import org.apache.poi.poifs.crypt.standard.*;
import org.apache.poi.xwpf.usermodel.*;
public class DocxWithPassword {
public static void main(String[] args) throws Exception {
String inputFilePath = "example.docx";
String outputFilePath = "example_password_protected.docx";
String password = "your_password_here";
try (FileInputStream fis = new FileInputStream(inputFilePath)) {
XWPFDocument document = new XWPFDocument(fis);
// 创建POIFS文档加密对象
POIFSFileSystem fs = new POIFSFileSystem();
EncryptionInfo info = new EncryptionInfo(EncryptionMode.xor);
// 创建加密对象
Encryptor encryptor = info.getEncryptor();
encryptor.confirmPassword(password);
// 使用加密对象对文档进行加密
try (FileOutputStream fos = new FileOutputStream(outputFilePath)) {
document.write(encryptor.getDataStream(fs));
fs.writeFilesystem(fos);
}
System.out.println("Document successfully encrypted with password: " + password);
}
}
}
将inputFilePath更改为要加密的.docx文件的路径,将outputFilePath更改为加密后的文件的输出路径,将password设置为所需的密码。现在运行程序,它将把输入文件加密并保存为带有密码的新文件。
领取专属 10元无门槛券
手把手带您无忧上云