我使用 Apache POI 框架生成了一个 xlsx 密码保护文件,下面添加了我的代码。但是,我无法使用 Excel 工具打开生成的文件。我可以使用 Plan Maker 免费工具打开它。欢迎任何建议。
我使用了以下罐子,commons-collections4-4.4.jar,commons-compress-1.20.jar,commons-math3-3.0.jar,poi-4.1.2.jar,poi-ooxml-4.1.2.jar,poi- ooxml-schemas-4.1.2.jar、SparseBitSet-1.1.jar、xmlbeans-3.1.0.jar
package com.pega.gcs.createworkbook;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ProtectedExcelFile {
public static void main(final String... args) throws Exception {
String fname = "FromJavaSecure1.xlsx";
String label="Sheet1-Abc";
String cellvalue="Cell1";
org.apache.poi.xssf.usermodel.XSSFSheet sheet;
org.apache.poi.xssf.usermodel.XSSFRow row;
org.apache.poi.xssf.usermodel.XSSFCell cell;
org.apache.poi.hssf.usermodel.HSSFSheet hsheet;
org.apache.poi.hssf.usermodel.HSSFRow hrow;
org.apache.poi.hssf.usermodel.HSSFCell hcell;
FileInputStream fileInput = null;
BufferedInputStream bufferInput = null;
POIFSFileSystem poiFileSystem = null;
FileOutputStream fileOut = null;
try {
try(
HSSFWorkbook workbook = new HSSFWorkbook();
)
{
hsheet=workbook.createSheet(label); hrow=hsheet.createRow(0);
hcell=hrow.createCell(0); hcell.setCellValue(cellvalue);
Biff8EncryptionKey.setCurrentUserPassword("secret");
fileOut = new FileOutputStream(fname);
workbook.writeProtectWorkbook(Biff8EncryptionKey.getCurrentUserPassword(), "");
workbook.write(fileOut);
}
}
catch (Exception ex) {
System.out.println(ex.getMessage());
}
finally {
/*
* try {
*
* bufferInput.close(); } catch (IOException ex) {
*
* System.out.println(ex.getMessage()); }
*
* try {
*
* fileOut.close(); } catch (IOException ex) {
*
* System.out.println(ex.getMessage()); }
*/
}
}
}