首先获得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();