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过程。
也可以转为输出流,做后续其他的流操作。
快速、简洁、解决大文件内存溢出的java处理Excel工具
最近提交(Master分支:4 个月前 )
c42183df
Bugfix 1 年前
efa7dff6 * 重新加回 `commons-io`
1 年前
AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。
更多推荐


所有评论(0)