目录
业务场景:与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);