java - Apache POI 加密的 xlsx 无法在 Excel 中打开

标签 java excel apache-poi xssf

我正在尝试使用 Apache POI 创建加密的 xlsx 文件。这是我的代码,运行得很好:

public static void Encrypt(String data) throws IOException, GeneralSecurityException, InvalidFormatException {

    Workbook wb = new XSSFWorkbook();
    Sheet sheet1 = wb.createSheet("sheet1");
    sheet1.createRow(0).createCell(0).setCellValue(data);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    wb.write(bos);
    bos.close();

    POIFSFileSystem fs = new POIFSFileSystem();
    EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile, CipherAlgorithm.aes256, HashAlgorithm.sha512, 256, 16, ChainingMode.cbc);
    Encryptor enc = info.getEncryptor();
    enc.confirmPassword("pass");

    OPCPackage opc = OPCPackage.open(new ByteArrayInputStream(bos.toByteArray()));
    OutputStream os = enc.getDataStream(fs);
    opc.save(os);
    opc.close();

    FileOutputStream fos = new FileOutputStream("provawrite.xlsx");
    fs.writeFilesystem(fos);
    fos.close();
}

问题是当我打开生成的文件时,Excel 不断提示文件已损坏。 我还尝试使用不同的加密模式更改 EncryptionInfo 实例化,但没有任何变化。

有人可以给我提示吗?!?

最佳答案

在写出文件系统之前必须关闭加密的输出流。在您的情况下,它在 opc.save(os); 之后缺少 os.close();

但是为什么要绕道使用ByteArrayOutputStream呢?

以下对我有用:

import java.io.*;
import org.apache.poi.poifs.filesystem.*;
import org.apache.poi.poifs.crypt.*;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class XSSFEncryption {

 public static void doEncrypt(String data) throws Exception {

  POIFSFileSystem fs = new POIFSFileSystem();
  EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile);

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

  Workbook workbook = new XSSFWorkbook();
  Sheet sheet = workbook.createSheet("sheet1");
  sheet.createRow(0).createCell(0).setCellValue(data);

  // write the workbook into the encrypted OutputStream
  OutputStream encos = enc.getDataStream(fs);
  workbook.write(encos);
  workbook.close();
  encos.close(); // this is necessary before writing out the FileSystem

  OutputStream os = new FileOutputStream("provawrite.xlsx");
  fs.writeFilesystem(os);
  os.close();
  fs.close();
 }

 public static void main(String[] args) throws Exception {
  doEncrypt("Test");
 }
}

关于java - Apache POI 加密的 xlsx 无法在 Excel 中打开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52428828/

相关文章:

regex - 无法在 vba IE 中应用正则表达式

java - XWPFDocument 循环替换段落

java - Apache POI 将日期本地化到 Excel 单元格中

Java 6 注解处理——从注解中获取类

java - 创建随机签名

java - 如何在android中制作一个没有控件的相机应用程序,以便屏幕上只显示镜头的 View ?

vba - 删除特定列中具有特定值的行

c# - 无法加载文件或程序集 'Microsoft.Office.Interop.Excel'

java - 错误 : How to read empty cell in Excel

java - 由于内部联接而不是左联接,Spring DTO 投影查询不会返回所有结果