標籤:form file 下載 exce container handle res while chm
頁面:<form action="${path}/xxx/xxx.do" method="get" > 表格下載:<input type="submit" value="下載"> </form>
@RequestMapping("/download")public void download(HttpServletRequest request, HttpServletResponse response, HttpSession session)throws Exception {ArrayList<String> listTitle = new ArrayList<String>();listTitle.add("a");listTitle.add("b");listTitle.add("c");listTitle.add("d");listTitle.add("e");// 建立表格及其第一列名欄HSSFWorkbook wb = new HSSFWorkbook();HSSFSheet sheet = wb.createSheet("sheet1");HSSFRow row0 = sheet.createRow(0);for (int j = 0; j < 5; j++) {// 5列HSSFCell cell = row0.createCell((short) j);cell.setCellValue(listTitle.get(j).toString());}String maker = SystemUtil.getCureenUser(session);List<MainfestItem> list = transportService.getlist(maker);System.out.println(list.size());// 從第二行輸入for (int i = 1; i <= list.size(); i++) { // 幾行HSSFRow row = sheet.createRow(i);HSSFCell cell0 = row.createCell((short) 0);// 第n+1個cell0.setCellValue(list.get(i - 1).getId().toString());HSSFCell cell1 = row.createCell((short) 1);cell1.setCellValue(list.get(i - 1).getContainerid().toString());HSSFCell cell2 = row.createCell((short) 2);cell2.setCellValue(list.get(i - 1).getIsocode().toString());}ByteArrayOutputStream os = new ByteArrayOutputStream();wb.write(os);byte[] content = os.toByteArray();InputStream is = new ByteArrayInputStream(content);// 設定response參數,可以開啟下載頁面response.reset();response.setContentType("application/vnd.ms-excel;charset=utf-8");response.setHeader("Content-Disposition","attachment;filename=" + new String(("box" + ".xls").getBytes(), "iso-8859-1"));ServletOutputStream out = response.getOutputStream();BufferedInputStream bis = null;BufferedOutputStream bos = null;try {bis = new BufferedInputStream(is);bos = new BufferedOutputStream(out);byte[] buff = new byte[2048];int bytesRead;// Simple read/write loop.while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {bos.write(buff, 0, bytesRead);}} catch (Exception e) {// TODO: handle exceptione.printStackTrace();} finally {if (bis != null)bis.close();if (bos != null)bos.close();}}
java寫簡單Excel 首行是目錄 然後前台下載