需求:需要从数据库查询出数据,生成excel,然后和若干其它在服务器存储的文件一同打包成zip文件,下载给用户。
实现:
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import java.io.OutputStream;
import java.io.FileInputStream;
public void exportMonitorScript(HttpServletRequest request, HttpServletResponse response) {
HSSFWorkbook workbook = new HSSFWorkbook();
//对workbook的内容就不具体写了
OutputStream out = null;
ZipOutputStream zipOut = null;
String zipName = new String(("工具包.zip").getBytes("UTF-8"), "ISO-8859-1");
response.setContentType("application/msexcel;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment; filename=" + zipName);
out = response.getOutputStream();
zipOut = new ZipOutputStream(out);
zipOut.putNextEntry(new ZipEntry(“用户信息” + ".xls"));
// 把excel写到out中
workbook.write(zipOut);
zipOut.closeEntry();
// 继续写其它文件
for (Map<String, Object> m : scriptList) {
//导出到zip中的文件名
String fileName = m.get("fileName") + "";
// 文件路径
String filePath = m.get("filePath") + "";
File file = new File(filePath);
this.zip(file, fileName, zipOut);
}
zipOut.close();
out.close();
}
private void zip(File file, String realName, ZipOutputStream zipOut) {
FileInputStream fis = null;
try {
byte[] buffer = new byte[1024];
fis = new FileInputStream(file);
zipOut.putNextEntry(new ZipEntry(realName));
int len;
// 读入需要下载的文件的内容,打包到zip文件
while ((len = fis.read(buffer)) > 0) {
zipOut.write(buffer, 0, len);
}
zipOut.closeEntry();
fis.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != fis) {
try {
fis.close();
} catch (IOException e) {
logger.error("Exception:" + e);
}
}
}
}