java导出zip文件

该代码示例展示了如何在Java中从数据库获取数据,创建Excel工作簿,然后将Excel与其他文件一起压缩成ZIP文件供用户下载。使用了ApachePOI处理Excel,Apache工具包处理ZIP压缩,并通过HttpServletRequest和HttpServletResponse进行HTTP响应。
摘要由CSDN通过智能技术生成

需求:需要从数据库查询出数据,生成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);
		}
	    }
	}

    }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值