多张excel打包成zip文件下载样例

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping
public class ManyExcelExport {

	@RequestMapping(value = "many/excel/export", method = RequestMethod.GET)
	public void manyExcelExport(HttpServletRequest request,HttpServletResponse response) {
		OutputStream out = null;
		ZipOutputStream zipOutputStream = null;
		String fileName = null;
		try {
			fileName = URLDecoder.decode("demo.zip", "UTF-8");
			response.setHeader("Content-Disposition", "attachment; filename="+fileName);	
			response.setContentType("application/octet-stream; charset=utf-8");			
			out = response.getOutputStream();	
			zipOutputStream = new ZipOutputStream(out);			
			for (int i = 0; i < 2; i++) {
				//从resources/templates下取得excel文件
				XSSFWorkbook workbook = new XSSFWorkbook(this.getClass().getResourceAsStream("/templates/demo"+(i+1)+".xlsx"));
				/**
				 * XSSFWorkbook的write()方法传去MemoryStream对象后,会自动关闭传入的参数,导致再次使用putNextEntry()方法报错:Stream closed	
				 * 解决方式:将XSSFWorkbook转换成ByteArrayOutputStream,用ByteArrayOutputStream对象将流写入zip对象中		
				 */
				ByteArrayOutputStream bos = new ByteArrayOutputStream();
				workbook.write(bos);
				ZipEntry entry = new ZipEntry("demo"+(i+1)+ ".xlsx");
				zipOutputStream.putNextEntry(entry);
				bos.writeTo(zipOutputStream);
				zipOutputStream.closeEntry();
				bos.close();
				workbook.close();
			}		
			out.flush();  
                        zipOutputStream.flush(); 		
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				if (zipOutputStream != null ) {
					zipOutputStream.close();
				}	
				if (out != null) {
					out.close();
				}				
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值