这是我第一个博客、也是人生中第一次写博客、很激动、也很紧张。新人初窥Java之路、有不足之处还请多多指教、相互学习。
Java 多文件Excel 导出为Zip 并下载:
1. 要想导出Zip文件、首先你必须将你指向的内容写入到文件中。创建一个向指定的File 对象表示的文件中写入数据的文件输出流。
@RequestMapping("/export)
public void export(HttpServletResponse response, HttpServletRequest request) {
List<WhiteList> personList = whiteListDao.getList(mp); // 从数据库查询数据,就不展示啦!
List<String> lstFile = new ArrayList<String>();
/**
* 得到图片字节流+数组大小
* filesPath 默认路径 ImagePath 图片
*/
for (int i = 0; i < personList.size(); i++) {
String fullPath = filesPath + personList.get(i).getImagePath();
lstFile.add(fullPath);
}
try{
// 准备向压缩文件放入的Excel文件的Stream
Workbook workbook = EasyExcelUtil.exportExcel(personList, "导出", "名单", "导出.xls",
response);
// 唯一ID
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
// 导出Xls的名字
String target = filesPath + "\\" + uuid + ".xls";
lstFile.add(target);
// 通过流将字节数据写入到文件中
File file = new File(target);
FileOutputStream stream = new FileOutputStream(file);
workbook.write(stream);
byte[] bufferOfZip = ExcelZipUtil.streamZipStream(target,lstFile);
// 解决导出时中文乱码的问题
response.setHeader("Content-Disposition",
"attachment;filename=" + new String(("导出" + ".zip").getBytes(), "iso-8859-1"));
response.getOutputStream().write(bufferOfZip);
}catch (IOException e) {
e.printStackTrace();
}
}
2. 将Excel文档内容压缩到zip文件中去。
public static byte[] streamZipStream(String target,List<String> lstFile) { // lstFile 指已生成的.xls文档
ZipOutputStream zos = null;
BufferedInputStream bis = null;
ByteArrayOutputStream fos = null;
try {
fos = new ByteArrayOutputStream();
zos = new ZipOutputStream(fos);
try {
for (String fileName : lstFile) {
InputStream input = new FileInputStream(fileName); // 定义文件的输入流
ZipEntry zipEntry = new ZipEntry(fileName);
//通过ZipOutputStream将内容写入到zip格式的文件中。期间如要需要加入什么文件。通过ZipEntry来添加。
zos.putNextEntry(zipEntry); // 创建压缩的子目录
int temp = 0;
while ((temp = input.read()) != -1) { // 读取内容
zos.write(temp); // 压缩输出
}
}
} finally {
zos.close(); // 不写的话会出Stream close 异常,提示未关闭文件流。
}
return fos.toByteArray();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// 关闭流
try {
if (null != fos)
fos.close();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
return null;
}
}