有时候会遇到需要在后台批量生成Excel并导出的应用场景,为了方便导出下载,通常会采用Zip打包成一个文件然后下载导出的方式实现。
1.导出Excel
之前写过一篇 POI 通用导出Excel(.xls,.xlsx),
所以此处不会再重复写导出Excel的方法,大家可以根据需要改写这个方法以适用自己的需求。
/**
* 导出Excel 2007 OOXML (.xlsx)格式
* @param title 标题行(可作为文件名)
* @param headMap 属性-列头
* @param jsonArray 数据集
* @param datePattern 日期格式,传null值则默认 年月日
* @param colWidth 列宽 默认 至少17个字节
* @param out 输出流
*/
public static void exportExcelX(String title,Map<String, String> headMap,JSONArray jsonArray,String datePattern,int colWidth, OutputStream out) ;
导出Excel方法的定义如上所示,headMap表示表格列头(当然可以用JSONObject替换),该方法最后将生成的Excel以输出流的方式存在内存当中。
在调用该方法时如果声明一个FileOutputStream并传入该方法,最后就以本地文件的方式保存excel;如果传入的是ServletOutputStream则可以返回给浏览器下载;如果传入的是ByteArrayOutputStream则以字节流的形式保存在内存中。
2.ZIP打包多个文件
zip打包多个文件的代码框架如下:
FileOutputStream fout = new FileOutputStream("test.zip");
ZipOutputStream zout = new ZipOutputStream(fout);
for all files
{
ZipEntry ze = new ZipEntry(filename);// file.getName();
zout.putNextEntry(ze);
send data to zout;
zout.closeEntry();
}
zout.close();
如果使用上面的循环文件列表的方式来打包到zip中,意味着生成的多个excel文件需要先保存为文件然后在使用文件IO流来读取文件,这样效率会很低且耗时长。所以可以将生成的excel文件以字节流的形式ByteArrayOutputStream保存在内存中,每生成一个就将它压缩到ZipOutputStream 流中,这样不经过IO读写速度会很快。
下面是zip打包单个excel文件的代码
/**
* 压缩单个excel文件的输出流 到zip输出流,注意zipOutputStream未关闭,需要交由调用者关闭之
* @param zipOutputStream zip文件的输出流
* @param excelOutputStream excel文件的输出流
* @param excelFilename 文件名可以带目录,例如 TestDir/test1.xlsx
*/
public static void compressFileToZipStream(ZipOutputStream zipOutputStream,
ByteArrayOutputStream excelOutputStream,String excelFilename) {
byte[] buf = new byte[1024];
try {
// Compress the files
byte[] content = excelOutputStream.toByteArray();
ByteArrayInputStream is = new ByteArrayInputStream(content);
BufferedInputStream bis = new BufferedInputStream(is);
// Add ZIP entry to output stream.
zipOutputStream.putNextEntry(new ZipEntry(excelFilename));
// Transfer bytes from the file to the ZIP file
int len;
while ((len = bis.read(buf)) > 0) {
zipOutputStream.write(buf, 0, len);
}
// Complete the entry
zipOutputStream.closeEntry();
bis.close();
is.close();
// Complete the ZIP file
} catch (IOException e) {
e.printStackTrace();
}
}
将内存中的ByteArrayOutputStream字节输出流转换成ByteArrayInputStream字节输入流,
然后读入到ZipOutputStream中。
zipOu