excel写为字节流使用base64加解密

目录

将实体类list组装成excel信息并使用base64加密

方式1:使用easyExcel得到字节流

方式2:使用ExcelWriter得到字节流

将base64加密串解析成excel信息


业务场景:与excel方交互,需要将list实体类生成一个excel文件,然后用base64加密成字符串交互。并且excel方修改完后,会同样生成base64加密的字符串传回来,我再根据此字符串解析到excel信息

思路:要是用base64加密,需要先将数据转成byte数组的形式才能去加密。那excel文件怎么才能得到字节数组呢,就需要拿到文件的字节流

将实体类list组装成excel信息并使用base64加密

无需生成excel文件,将内容写入到字节流中即可,字节流再去使用base64加密

方式1:使用easyExcel得到字节流

依赖包

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
    <version>3.0.5</version>
</dependency>

使用easyExcel将结果集写到字节流中,得到字节数组加密

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
// 使用easyexcel,将信息写入到byte流中
EasyExcel.write(byteArrayOutputStream, AllotTaskResult.class).sheet(SHEET_NAME).doWrite(buildAllotTaskResultList(list));
// 加密字节数组
String excelContent = Base64Utils.encodeToString(byteArrayOutputStream.toByteArray());

方式2:使用ExcelWriter得到字节流

依赖包

<!-- 基本依赖包 -->
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.3.8</version>
</dependency>
<!-- Excel包 -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.2</version>
</dependency>

根据结果集list设置表头, 使用excelWriter将内容写出到第一个sheet,通过flush将内容写出到字节流中,得到字节数据加密

ExcelWriter writer = ExcelUtil.getBigWriter();
//设置表头,注意!!!参数1为实体类字段,参数2为excel生成的表头
writer.addHeaderAlias("one", "第一列");
writer.addHeaderAlias("two", "第二列");
//... 

writer.write(buildAllotTaskResultList(list));
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//刷出到字节输出流中
writer.flush(byteArrayOutputStream);
String excelContent = Base64Utils.encodeToString(byteArrayOutputStream.toByteArray());

将base64加密串解析成excel信息

无需生成excel,拿到字节流后直接根据实体类读成list

base64加密串,使用excelReader解析到excel内容

byte[] bytes = Base64Utils.decodeFromString(excelContent);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayInputStream(bytes);

//读字节流
ExcelReader reader = ExcelUtil.getReader(byteArrayOutputStream);
//设置excel表头,注意!!!参数1为excel表头,参数2为实体类字段
reader.addHeaderAlias("第一列", "one");
reader.addHeaderAlias("第二列", "two");
// ... 

//将字节流读成excel行记录
List<AllotTaskResult> allotTaskResults = reader.readAll(AllotTaskResult.class);
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值