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();
}
}
}
}