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 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

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值