java poi 加密 示例代码
时间: 2023-07-09 07:05:52 浏览: 47
下面是使用 Java POI 进行 Excel 文件加密的示例代码:
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
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;
public class EncryptExcelFile {
public static void main(String[] args) throws Exception {
// 加载 Excel 文件
FileInputStream fis = new FileInputStream(new File("example.xlsx"));
Workbook workbook = new XSSFWorkbook(fis);
fis.close();
// 创建 EncryptionInfo 和 Encryptor 对象
EncryptionInfo info = new EncryptionInfo(EncryptionInfo.VERSION_AES_256);
Encryptor enc = info.getEncryptor();
// 加密 Excel 文件
enc.confirmPassword("password");
POIFSFileSystem fs = new POIFSFileSystem();
enc.encryptDocument(new FileInputStream("example.xlsx"), fs);
FileOutputStream fos = new FileOutputStream("encrypted.xlsx");
fs.writeFilesystem(fos);
fos.close();
}
}
```
在上面的示例代码中,我们首先加载 Excel 文件并创建 EncryptionInfo 和 Encryptor 对象,然后使用 `enc.confirmPassword()` 方法指定加密密码,最后使用 `enc.encryptDocument()` 方法将 Excel 文件加密并写入到新文件中。