java 导出表格打包zip文件下载_POI多个工作簿导出表格打包ZIP下载

这篇博客介绍了如何在Java中使用Apache POI库将多个Excel工作簿打包成ZIP文件供下载。首先创建一个`zipFiles`方法,它接收工作簿列表、目标ZIP文件和文件名前缀,通过`ZipOutputStream`将每个工作簿写入ZIP文件。为了避免`Workbook`的`write()`方法自动关闭流,使用了`ByteArrayOutputStream`进行中间转换。然后,定义了一个`downFile`方法,用于设置HTTP响应头并发送ZIP文件内容到客户端进行下载。最后,通过`ClassController`类调用这两个方法实现文件的导出和下载。
摘要由CSDN通过智能技术生成

首先获得workbook集合对象

public static void zipFiles(List srcfile, File zipfile,String fileName) {

try {

ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));

for (int i = 0; i < srcfile.size(); i++) {

ZipEntry entry = new ZipEntry(fileName+i+".xls");

out.putNextEntry(entry);

ByteArrayOutputStream bos = new ByteArrayOutputStream();

srcfile.get(i).write(bos);

bos.writeTo(out);

out.closeEntry();

bos.close();

}

out.flush();

out.close();

} catch (IOException e) {

e.printStackTrace();

}

}

将多个workbook工作簿添加到ZipOutputStream中。(特别要注意此处的out.putNextEntry(entry);如果直接使用Workbook的write()方法,会自动关闭传入的参数,导致再次使用putNextEntry()方法是报错Stream closed。所以此处使用了

ByteArrayOutputStream 进行包装)

public static HttpServletResponse downFile(HttpServletResponse response, File file) {

try {

// 以流的形式下载文件。

InputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));

byte[] buffer = new byte[fis.available()];

fis.read(buffer);

fis.close();

// 清空response

response.reset();

OutputStream toClient = new BufferedOutputStream(response.getOutputStream());

response.setContentType("application/x-zip-compressed");

response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));

toClient.write(buffer);

toClient.flush();

toClient.close();

} catch (IOException ex) {

ex.printStackTrace();

}

return null;

}

客户端下载文件

File temp = File.createTempFile("temp",".zip");

ClassController.zipFiles(workbooks,temp,"考勤表");

rep = ClassController.downFile(rep, temp);

temp.deleteOnExit();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值