POI加密Excel文件导出

使用的包:

<dependency>
	<groupId>org.apache.poigroupId>
	<artifactId>poi-ooxmlartifactId>
	<version>4.1.0version>
	<scope>providedscope>
dependency>

使用xlsx格式(excel 2007版本以后的格式)

poi官方文档的例子的使用agile加密,用 OPCPackage 这个东西将内容写入文件流,但是我用了之后加密是成功了,文件却打不开了。
百度了很多答案都是和官方例子一样。

最后在这找到了答案,需要
https://stackoverflow.com/questions/52428828/apache-poi-encrypted-xlsx-cannot-be-opened-in-excel

核心代码


           POIFSFileSystem fs = new POIFSFileSystem();
           EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile);
// final EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile, CipherAlgorithm.aes256, HashAlgorithm.sha256, -1, -1, null);
            Encryptor enc = info.getEncryptor();
//set the password
            // OPCPackage opc = OPCPackage.open(new File(path),PackageAccess.READ_WRITE); 官方文档的例子用的这个,贼坑
            if(StringUtils.isBlank(password)){
                enc.confirmPassword("11111");
            }else {
                enc.confirmPassword(password);
            }

            OutputStream os = enc.getDataStream(fs);
            wb.write(os);
            os.close();

            FileOutputStream fos = new FileOutputStream(path);
            fs.writeFilesystem(fos);
            fos.close();

完整代码:

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");
 }
}

你可能感兴趣的:(POI)