EasyExcel转化为byte[]、inputStream或者OutputStream
easyexcel
快速、简洁、解决大文件内存溢出的java处理Excel工具
项目地址:https://gitcode.com/gh_mirrors/ea/easyexcel
免费下载资源
·
- 场景:需要生成excel文件,并且存储到文件服务器
转为字节数组(生成excel)
public static byte[] ListToExcelOutPutStream(List<?> lst, Class clazz) {
ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
ExcelWriter excelWriter = EasyExcel.write(arrayOutputStream,clazz).build();
WriteSheet writeSheet = EasyExcel.writerSheet().build();
excelWriter.write(lst, writeSheet);
excelWriter.finish();
return arrayOutputStream.toByteArray();
}
- 转为字节数组(模板填充)
String templateFileName = this.getClass().getClassLoader().getResource("test.xlsx").getPath();
List<Map> mapList = new ArrayList<>();
Map map = new HashMap<>();
map.put("name","zhanghao");
map.put("number","18");
mapList.add(map);
ByteArrayOutputStream os = new ByteArrayOutputStream();
ExcelWriter excelWriter = EasyExcel.write().withTemplate(templateFileName).file(os).build();
WriteSheet writeSheet = EasyExcel.writerSheet().build();
excelWriter.fill(mapList, writeSheet);
excelWriter.finish();
byte[] buffer = os.toByteArray();
- 转为outputstream(模板填充)
String templateFileName = this.getClass().getClassLoader().getResource("test.xlsx").getPath();
List<Map> mapList = new ArrayList<>();
Map map = new HashMap<>();
map.put("name","zhanghao");
map.put("number","18");
mapList.add(map);
ByteArrayOutputStream os = new ByteArrayOutputStream();
ExcelWriter excelWriter = EasyExcel.write().withTemplate(templateFileName).file(os).build();
WriteSheet writeSheet = EasyExcel.writerSheet().build();
excelWriter.fill(mapList, writeSheet);
excelWriter.finish();
OutputStream outputStream = excelWriter.writeContext().writeWorkbookHolder().getOutputStream();
- 转为inputStream(模板填充)
String templateFileName = this.getClass().getClassLoader().getResource("test.xlsx").getPath();
List<Map> mapList = new ArrayList<>();
Map map = new HashMap<>();
map.put("name","zhanghao");
map.put("number","18");
mapList.add(map);
ByteArrayOutputStream os = new ByteArrayOutputStream();
ExcelWriter excelWriter = EasyExcel.write().withTemplate(templateFileName).file(os).build();
WriteSheet writeSheet = EasyExcel.writerSheet().build();
excelWriter.fill(mapList, writeSheet);
excelWriter.finish();
byte[] buffer = os.toByteArray();
InputStream inputStream = new ByteArrayInputStream(buffer);
- 总结
根据官方文档,正常情况下EasyExcel是将文件生成到本地,如果需要再操作,需要将文件转化为inputStream。
我们利用ByteArrayOutputStream为缓存,先将文件写入其中,然后将其转为字节数组,最后利用ByteArrayInputStream转为输入流,这样做省略了存储文件到本地的流程,省略了2个IO过程。
也可以转为输出流,做后续其他的流操作。
GitHub 加速计划 / ea / easyexcel
14
5
下载
快速、简洁、解决大文件内存溢出的java处理Excel工具
最近提交(Master分支:4 个月前 )
c42183df
Bugfix 4 个月前
efa7dff6 * 重新加回 `commons-io`
4 个月前
更多推荐
已为社区贡献1条内容
所有评论(0)