使用 spire.xls.jar 对 xlsx 设置打开密码和取消打开密码
时间: 2024-02-03 21:14:49 浏览: 23
抱歉,spire.xls.jar 不支持对 xlsx 文件设置打开密码和取消打开密码。你可以尝试使用 Apache POI 或者其他类似的库来实现该功能。以下是使用 Apache POI 设置 xlsx 文件打开密码的示例代码:
```
import org.apache.poi.poifs.crypt.EncryptionInfo;
import org.apache.poi.poifs.crypt.Encryptor;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileOutputStream;
public class XlsxEncryptionExample {
public static void main(String[] args) throws Exception {
// 加载 xlsx 文件
File inputFile = new File("example.xlsx");
Workbook workbook = new XSSFWorkbook(inputFile);
// 设置加密信息
EncryptionInfo encryptionInfo = new EncryptionInfo(EncryptionInfo.VERSION_AES_128);
Encryptor encryptor = encryptionInfo.getEncryptor();
encryptor.confirmPassword("password123");
// 加密文件
POIFSFileSystem fileSystem = new POIFSFileSystem();
encryptor.encryptDocument(fileSystem, workbook);
// 保存加密后的文件
File outputFile = new File("example_encrypted.xlsx");
try (FileOutputStream fos = new FileOutputStream(outputFile)) {
fileSystem.writeFilesystem(fos);
}
}
}
```
要取消 xlsx 文件的打开密码,只需要删除 `workbook.getCTWorkbook().getWorkbookProtection()` 中的 `workbookProtection` 元素即可。以下是示例代码:
```
import org.apache.poi.poifs.crypt.Decryptor;
import org.apache.poi.poifs.crypt.EncryptionInfo;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class XlsxDecryptionExample {
public static void main(String[] args) throws Exception {
// 加载加密后的 xlsx 文件
File inputFile = new File("example_encrypted.xlsx");
POIFSFileSystem fileSystem = new POIFSFileSystem(new FileInputStream(inputFile));
EncryptionInfo encryptionInfo = new EncryptionInfo(fileSystem);
Decryptor decryptor = Decryptor.getInstance(encryptionInfo);
// 解密文件
if (!decryptor.verifyPassword("password123")) {
throw new RuntimeException("Invalid password");
}
try (FileOutputStream fos = new FileOutputStream("example_decrypted.xlsx")) {
decryptor.getDataStream(fileSystem).transferTo(fos);
}
// 加载解密后的 xlsx 文件
Workbook workbook = new XSSFWorkbook(new FileInputStream("example_decrypted.xlsx"));
// 取消打开密码
workbook.getCTWorkbook().unsetWorkbookProtection();
// 保存取消打开密码后的文件
try (FileOutputStream fos = new FileOutputStream("example_no_password.xlsx")) {
workbook.write(fos);
}
}
}
```