java读取加密excel,读取密码保护的Excel文件(.xlsx)格式使用Java

I have tried the below code,

import org.apache.poi.poifs.crypt.Decryptor;

import org.apache.poi.poifs.crypt.EncryptionInfo;

import org.apache.poi.poifs.filesystem.POIFSFileSystem;

POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream("D://protectedfile.xlsx"));

EncryptionInfo info = new EncryptionInfo(fs);

Decryptor d = new Decryptor(info); //Error

d.verifyPassword(Decryptor.DEFAULT_PASSWORD);

It throws an error compilation error : Cannot instantiate the type Decryptor

But eventually this method will need me to copy and create new workbook in which i can read the data.

Why i'm not able to instantiate Decryptor?

Is there any other way than this, so that i can simply read the password protected excel file without creating a copy of it?

Note : I have looked at this post reading excel file, but doesn't help my exact situation

解决方案

Ah, I've spotted your problem. It's this line:

Decryptor d = new Decryptor(info);

As shown in the Apache POI Encryption documentation, that line needs to be

Decryptor d = Decryptor.getInstance(info);

You'd be well advised to review the POI docs on encryption, and also make sure you're using the latest version of Apache POI (3.11 beta 2 as of writing)

Additionally, opening a File from an InputStream isn't recommended, as per the documentation, as it's slower and higher memory (everything has to get buffered). Instead, your code should really be:

NPOIFSFileSystem fs = new NPOIFSFileSystem(new File("D://protectedfile.xlsx"));

EncryptionInfo info = new EncryptionInfo(fs);

Decryptor d = Decryptor.getInstance(info);

if (d.verifyPassword("password")) {

XSSFWorkbook wb = new XSSFWorkbook(d.getDataStream(fs));

} else {

// Password is wrong

}

Finally, get the decrypted data, and pass that to XSSFWorkbook to read the encrypted workbook

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值