여러 장의 excel을 zip 파일로 포장하여 다운로드 예시

2234 단어 io
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();
			}
		}
	}
	
}

좋은 웹페이지 즐겨찾기