• 场景:需要生成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 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐