gpt4 book ai didi

java - 在 XSSF 工作簿上设置密码保护

转载 作者:行者123 更新时间:2023-11-30 08:31:44 61 4
gpt4 key购买 nike

我想为使用 poi 3.14 创建的 xlsx 文件添加密码保护。文档声称,这是可能的:

http://poi.apache.org/encryption.html

使用我这样尝试的示例:

    public static void main(String[] args)
{
try(Workbook wb = new XSSFWorkbook())
{

//<...>
try(ByteArrayOutputStream baos = new ByteArrayOutputStream())
{
wb.write(baos);
byte[] res = baos.toByteArray();
try(ByteArrayInputStream bais = new ByteArrayInputStream(res))
{
try(POIFSFileSystem fileSystem = new POIFSFileSystem(bais);) // Exception happens here
{
EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile);
Encryptor enc = info.getEncryptor();
enc.confirmPassword("pass");
OutputStream encryptedDS = enc.getDataStream(fileSystem);
OPCPackage opc = OPCPackage.open(new File("example.xlsx"), PackageAccess.READ_WRITE);
opc.save(encryptedDS);
opc.close();
}
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}

不幸的是,示例中的代码与 XLSX 文件不兼容,因此我收到以下异常:

The supplied data appears to be in the Office 2007+ XML. You are calling the part of POI that deals with OLE2 Office Documents. You need to call a different part of POI to process this data (eg XSSF instead of HSSF)

有人可以帮忙吗?我找不到 XLSX 的正确替代品...

谢谢大家的帮助。这是我的工作结果:

    public static void main(String[] args)
{
try(Workbook wb = new XSSFWorkbook())
{
Sheet sheet = wb.createSheet();
Row r = sheet.createRow(0);
Cell cell = r.createCell(0);
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue("Test");
try(POIFSFileSystem fileSystem = new POIFSFileSystem();)
{
EncryptionInfo info = new EncryptionInfo(EncryptionMode.standard);
Encryptor enc = info.getEncryptor();
enc.confirmPassword("pass");
OutputStream encryptedDS = enc.getDataStream(fileSystem);
wb.write(encryptedDS);
FileOutputStream fos = new FileOutputStream("C:/example.xlsx");
fileSystem.writeFilesystem(fos);
fos.close();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}

最佳答案

您误读了 documentation on encrypting in OOXML file .因此,当您只需要保存文件时,您会错误地尝试使用错误的代码加载文件

没有任何错误处理,你的代码基本上就是

// Prepare
POIFSFileSystem fs = new POIFSFileSystem();
EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile, CipherAlgorithm.aes192, HashAlgorithm.sha384, -1, -1, null);

Encryptor enc = info.getEncryptor();
enc.confirmPassword("foobaa");

// Create the normal workbook
Workbook wb = new XSSFWorkbook();
Sheet s = wb.createSheet();
// TODO Populate

// Encrypt
OutputStream os = enc.getDataStream(fs);
wb.save(os);
opc.close();

// Save
FileOutputStream fos = new FileOutputStream("protected.xlsx");
fs.writeFilesystem(fos);
fos.close();

关于java - 在 XSSF 工作簿上设置密码保护,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40511701/

61 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com