admin管理员组

文章数量:1530884

2023年12月12日发(作者:)

excel加密的两种实现方式

文章目录

前言

在一些政府之类的项目中,对于导出文件的安全性相当重视,通常会要求对导出文件进行加密,这里提供两种excel的加密方式

一、基于poi的excel加密实现

这个方法是基于poi导出excel时对excel进行加密,这里要求excel的版本是2007以后即poi导出excel时使用的是XSSFWorkbook,这种方式

不需要中间缓存,直接是针对流的操作

/***

* @Author luo

* @Description //excel

加密

excel-2007

以后

* @Date 2020/10/29 10:19

* @param bos excel

输出流

* @param pwd

密码

* @return rayOutputStream

**/

public static ByteArrayOutputStream encryptExportExcel(ByteArrayOutputStream bos, String pwd) throws IOException, GeneralSecurityException, Invali

dFormatException {

POIFSFileSystem poifsFileSystem = new POIFSFileSystem();

EncryptionInfo encryptionInfo = new EncryptionInfo(rd);

Encryptor encryptor = ryptor();

mPassword(pwd);

OPCPackage opcPackage = (new ByteArrayInputStream(Array()));

OutputStream outputStream = aStream(poifsFileSystem);

(outputStream);

();

ByteArrayOutputStream resultbos = new ByteArrayOutputStream();

ilesystem(resultbos);

();

();

return resultbos;

}

二、基于jxcell的操作

1.引入jar包

在lib目录下添加包

2.代码实现

代码如下:

long start = tTimeMillis();

try {

//

源文件

(excel)

File src = new File("e:");

//

缓存文件

(

加密后的

excel)

File desc = new File("e:");

//

这里是从本地文件获取输入流

,

真实项目中可以将

excel

生成到服务器下的指定路径

FileInputStream fis = new FileInputStream(src);

FileOutputStream fos =new FileOutputStream(desc);

//

实现加密

View m_view = new View();

m_(fis);

// set the workbook open password

m_(fos, "111");

//

将缓存文件写回

,

这里指定了路径

,

实际开发可以直接指定到输出流

FileInputStream cache = new FileInputStream(desc);

FileOutputStream exportos =new FileOutputStream(new File("e:"));

byte[] b = new byte[1024*1024];

int len = -1;

while((len=(b))!=-1){

(b, 0, len);

();

}

();

();

();

();

} catch (IOException e) {

tackTrace();

}

long end = tTimeMillis();

n("共用时:"+(end-start)+"秒");

}

总结

本文标签: 加密文件指定导出要求