#java专栏#
-
背景
通过EasyExcel进行多个ExcelTypeEnum.XLSX类型Excel写入ZIP流时会发生Stream closed异常,以下通过使用ByteArrayOutputStream字节数组输出流完成多Excel.XLSX类型的压缩并输出
1、引入相关依赖(easyexcel)
com.alibaba
easyexcel
2、定义数据模型(ExcelData)
@Data
public class ExcelData {
private String name;
private int age;
2、定义将excel文件写入指定输出流方法
private static void writerStream(OutputStream outputStream) {
ExcelWriter excelWriter =EasyExcel.write(outputStream,ExcelData.class)
.excelType(ExcelTypeEnum.XLSX).build();
WriteSheet writeSheet = EasyExcel.writerSheet("sheetName").build();
excelWriter.write(getData(), writeSheet);
excelWriter.finish();
3、执行main方法
public static void main(String[] args) throws IOException {
FileOutputStream fos = new FileOutputStream(filePath);
ZipOutputStream zos = new ZipOutputStream(fos);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
writerStream(baos);
ZipEntry zipEntry = new ZipEntry("第一个excel.xlsx");
zos.putNextEntry(zipEntry);
zos.write(baos.toByteArray());
baos.reset();
ZipEntry zipEntry2 = new ZipEntry("第二个excel.xlsx");
zos.putNextEntry(zipEntry2);
baos.close();
zos.close();
-
注意事项
本文直接将异常处理抛出,实际应用中需要注意异常的处理
特别声明:以上内容(如有图片或视频亦包括在内)为自媒体平台“网易号”用户上传并发布,本平台仅提供信息存储服务。
Notice: The content above (including the pictures and videos if any) is uploaded and posted by a user of NetEase Hao, which is a social media platform and only provides information storage services.