一、代码
public static void exportXlsx2Zip(String fileName, List<Workbook> workbookList, HttpServletResponse response) throws IOException {
// 1、创建临时zip文件
String zipPath = "";
File zipFile = new File(zipPath + fileName + ".zip");
zipFile.createNewFile();
FileOutputStream f = new FileOutputStream(zipFile);
CheckedOutputStream csum = new CheckedOutputStream(f, new Adler32());
ZipOutputStream zos = new ZipOutputStream(csum);
try {
InputStream is = null;
Iterator<Workbook> iterator = workbookList.stream().iterator();
while (iterator.hasNext()) {
try {
Workbook workbook = iterator.next();
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
workbook.write(os);
} catch (IOException e) {
e.printStackTrace();
}
byte[] content = os.toByteArray();
// 1(3)、写入输入流
is = new ByteArrayInputStream(content);
// 1(4)、压入zip
zos.putNextEntry(new ZipEntry(fileName));
int bytesRead = 0;
while ((bytesRead = is.read()) != -1) {
zos.write(bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
is.close();
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
zos.closeEntry();
// 这里不能忘了
zos.close();
csum.close();
f.close();
}
// 要在zos.close()后
response.setContentType("application/zip");
response.addHeader("Pargam", "no-cache");
response.addHeader("Cache-Control", "no-cache");
response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(fileName + ".zip", "UTF-8"));
try (FileInputStream inputStream = new FileInputStream(zipFile)) {
IOUtils.copy(inputStream, response.getOutputStream());
}
}
二、问题汇总
1、poi过时方法:
cell.getCellType ();
去官方文档看了下
当时是因为该方法返回 int 不安全,所以加了个 getCellTypeEnum() 方法返回了枚举类。然后4.0以上版本修复了这个问题。
2、压缩失败:
打开压缩文件显示:
不可预料的压缩文件末端