前言
在一些政府之类的项目中,对于导出文件的安全性相当重视,通常会要求对导出文件进行加密,这里提供两种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 java.io.ByteArrayOutputStream
**/
public static ByteArrayOutputStream encryptExportExcel(ByteArrayOutputStream bos, String pwd) throws IOException, GeneralSecurityException, InvalidFormatException {
POIFSFileSystem poifsFileSystem = new POIFSFileSystem();
EncryptionInfo encryptionInfo = new EncryptionInfo(EncryptionMode.standard);
Encryptor encryptor = encryptionInfo.getEncryptor();
encryptor.confirmPassword(pwd);
OPCPackage opcPackage = OPCPackage.open(new ByteArrayInputStream(bos.toByteArray()));
OutputStream outputStream = encryptor.getDataStream(poifsFileSystem);
opcPackage.save(outputStream);
opcPackage.close();
ByteArrayOutputStream resultbos = new ByteArrayOutputStream();
poifsFileSystem.writeFilesystem(resultbos);
resultbos.flush();
resultbos.close();
return resultbos;
}
二、基于jxcell的操作
1.引入jar包
在lib目录下添加jxcell.jar包
jar包下载地址
2.代码实现
代码如下:
long start = System.currentTimeMillis();
try {
//源文件(excel)
File src = new File("e:\\123.xls");
//缓存文件(加密后的excel)
File desc = new File("e:\\456.xls");
//这里是从本地文件获取输入流,真实项目中可以将excel生成到服务器下的指定路径
FileInputStream fis = new FileInputStream(src);
FileOutputStream fos =new FileOutputStream(desc);
//实现加密
View m_view = new View();
m_view.read(fis);
// set the workbook open password
m_view.write(fos, "111");
//将缓存文件写回,这里指定了路径,实际开发可以直接指定到输出流
FileInputStream cache = new FileInputStream(desc);
FileOutputStream exportos =new FileOutputStream(new File("e:\\789.xls"));
byte[] b = new byte[1024*1024];
int len = -1;
while((len=cache.read(b))!=-1){
exportos.write(b, 0, len);
exportos.flush();
}
exportos.close();
cache.close();
fos.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
long end = System.currentTimeMillis();
System.out.println("共用时:"+(end-start)+"秒");
}
总结
两种方式都能实现excel的加密操作,具体实现需要根据项目导出excel是选用的技术来确定
jar包下载路径
https://download.csdn.net/download/catch_exception/13081119