jsp中下載Excel
此處使用JavaScript的open()函數,後台使用jxl動態產生Excel檔案流。
前台:window.opne("downExcelAction");
後台:
public void downExcelAction() throws RowsExceededException, WriteException{ System.out.println("【匯出EXCEL表格】"); String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".xls"; String result = "success"; //查詢出資料 //填充到excel中 OutputStream os; WritableWorkbook wbook; try { os = response.getOutputStream(); response.reset();// 清空輸出資料流 response.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes("GB2312"), "ISO8859_1"));// 設定輸出檔案頭,<span style="font-size:18px;color:#FF6666;">此處可以解決檔案名稱中文亂碼問題</span> response.setContentType("application/vnd.ms-excel");// 定義輸出類型 wbook = Workbook.createWorkbook(os);//建立excel檔案 WritableSheet wsheet = wbook.createSheet("會員卡資訊", 0);//建立sheet //定義儲存格樣式 WritableFont wf = new WritableFont(WritableFont.ARIAL, 12, WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE, jxl.format.Colour.BLUE); WritableCellFormat wcf = new WritableCellFormat(wf); //設定對齊 wcf.setAlignment(jxl.format.Alignment.CENTRE); //凍結第一行 wsheet.getSettings().setVerticalFreeze(1); wsheet.addCell(new Label(0, 0, "內碼", wcf)); wsheet.addCell(new Label(1, 0, "會員卡", wcf)); wsheet.addCell(new Label(2, 0, "代理商", wcf)); wsheet.addCell(new Label(3, 0, "會員卡資訊", wcf)); wsheet.addCell(new Label(4, 0, "會員卡狀態", wcf)); wsheet.addCell(new Label(5, 0, "消費資訊", wcf)); wsheet.addCell(new Label(6, 0, "當前餘額", wcf)); wsheet.addCell(new Label(7, 0, "時間", wcf)); //返回excel wbook.write(); wbook.close(); os.close(); } catch (Exception e) { result = "下載出現異常,請聯絡管理員。"; e.printStackTrace(); } }