1. 程式人生 > 其它 >Java新建excel檔案

Java新建excel檔案

本隨筆包含建立excel檔案、儲存在本地,或通過超連結和form表單下載兩種寫法,為個人筆記

· 新建excel檔案,並寫入資料,同時儲存在本地

/**
 * 將資料存入臨時的excel檔案並儲存在臨時資料夾中
 * @param response
 * @param paramList
 */
private void generateTempExcel(HttpServletRequest request, List<Map<String, Object>> paramList, Map<String, Object> resultMap) {
	FileOutputStream fos = null;
	WritableWorkbook wbook = null;
	try {
		// 檔名稱
		String templatePath = request.getSession().getServletContext().getRealPath("/template/");
		long nanoTime = System.nanoTime();
    	     String fileName = templatePath + "電子卡單批量查詢結果-" + nanoTime + ".xls";
    	     String downloadUrl = "/template/電子卡單批量查詢結果-" + nanoTime + ".xls";  // 域名加該地址即可訪問到檔案
    	     logger.info("電子卡單批量查詢結果檔名稱:" + fileName);
		/*StringBuffer fileName = new StringBuffer();
		fileName.append("電子卡單批量查詢結果");*/
		fos = new FileOutputStream(fileName);// 取得輸出流

		wbook = Workbook.createWorkbook(fos); // 建立excel檔案
		WritableSheet wsheet = wbook.createSheet("卡單啟用結果", 0); // sheet名稱

		// 設定excel標題
		WritableFont wfont = new WritableFont(WritableFont.ARIAL, 14, WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE);

		WritableCellFormat wcfFC = new WritableCellFormat(wfont);
		wcfFC.setWrap(true);
		wcfFC.setAlignment(Alignment.CENTRE);// 把水平對齊方式指定為居中
		wcfFC.setVerticalAlignment(VerticalAlignment.CENTRE);// 把垂直對齊方式指定為居中
		wcfFC.setBackground(Colour.GRAY_25); // 設定單元格的顏色為藍灰色
		wcfFC.setBorder(Border.ALL, BorderLineStyle.THIN); // 設定邊框

		wsheet.setRowView(0, 500, false); // 設定行高
		wsheet.setColumnView(0, 20);// 設定列寬(25個字元寬)
		wsheet.setColumnView(1, 30);
		wsheet.setColumnView(2, 20);
		wsheet.addCell(new Label(0, 0, "卡單啟用結果", wcfFC));
		wsheet.addCell(new Label(0, 1, "agentCode", wcfFC));
		wsheet.addCell(new Label(1, 1, "卡號", wcfFC));
		wsheet.addCell(new Label(2, 1, "啟用狀態", wcfFC));
		// 合併單元格
		wsheet.mergeCells(0, 0, 2, 0);
		wfont = new WritableFont(WritableFont.ARIAL, 12, WritableFont.NO_BOLD, false, UnderlineStyle.NO_UNDERLINE);
		wcfFC = new WritableCellFormat(wfont);
		wcfFC.setAlignment(Alignment.CENTRE);// 把水平對齊方式指定為居中
		wcfFC.setVerticalAlignment(VerticalAlignment.CENTRE);// 把垂直對齊方式指定為居中
		wcfFC.setWrap(true);
		wcfFC.setBorder(Border.ALL, BorderLineStyle.THIN); // 設定邊框

		jxl.write.NumberFormat nf = new jxl.write.NumberFormat("#0.0##"); // 設定數字格式
		jxl.write.WritableCellFormat wcfN = new jxl.write.WritableCellFormat(
				nf); // 設定表單格式
		wcfN.setWrap(true);
		wcfN.setBorder(Border.ALL, BorderLineStyle.THIN); // 設定邊框
		wcfN.setFont(wfont);

		// 開始生成主體內容
		for (int i = 0; i < paramList.size(); i++) {
			EcBatchDetailPaid ecBatchDetailPaid = (EcBatchDetailPaid)paramList.get(i);
			if (ecBatchDetailPaid == null) {
				continue;
			}
			wsheet.addCell(new Label(0, i + 2, ecBatchDetailPaid.getAgentCode() != null ? ecBatchDetailPaid.getAgentCode() : "-", wcfFC));
			wsheet.addCell(new Label(1, i + 2, ecBatchDetailPaid.getCertificationPrintNo() != null ? ecBatchDetailPaid.getCertificationPrintNo() : "-", wcfFC));
			String activeFlag = ecBatchDetailPaid.getActiveFlag();
			if ("0".equals(activeFlag)) {
				activeFlag = "未啟用";
			} else if ("1".equals(activeFlag)) {
				activeFlag = "已啟用";
			} else {
				activeFlag = "-";
			}
			wsheet.addCell(new Label(2, i + 2, activeFlag, wcfFC));
		}
		
		// 主體內容生成結束
		wbook.write(); // 寫入檔案
		resultMap.put("downloadUrl", downloadUrl);
	} catch (Exception ex) {
		ex.printStackTrace();
	} finally {
		try {
			if (wbook != null) {
				wbook.close();
			}
			if (fos != null) {
				fos.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

  

· 新建excel檔案,並寫入資料,同時支援前端直接通過超連結或者form表單下載

/**
 * 匯出的excel檔案
 */
private void ecardBatchSearchResultExportExcel(HttpServletResponse response, List<Map<String, String>> paramList) {
	BufferedOutputStream out = null;
	WritableWorkbook wbook = null;
	try {
		// 檔名稱
		StringBuffer fileName = new StringBuffer();
		fileName.append("電子卡單批量查詢結果");
		out = new BufferedOutputStream(response.getOutputStream());// 取得輸出流
		response.reset();// 清空輸出流

		response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName.toString() + ".xls", "UTF8"));// 這裡設定一下讓瀏覽器彈出下載提示框,而不是直接在瀏覽器中開啟

		wbook = Workbook.createWorkbook(out); // 建立excel檔案
		WritableSheet wsheet = wbook.createSheet("卡單啟用結果", 0); // sheet名稱

		// 設定excel標題
		WritableFont wfont = new WritableFont(WritableFont.ARIAL, 14, WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE);

		WritableCellFormat wcfFC = new WritableCellFormat(wfont);
		wcfFC.setWrap(true);
		wcfFC.setAlignment(Alignment.CENTRE);// 把水平對齊方式指定為居中
		wcfFC.setVerticalAlignment(VerticalAlignment.CENTRE);// 把垂直對齊方式指定為居中
		wcfFC.setBackground(Colour.GRAY_25);// 設定單元格的顏色為藍灰色
		wcfFC.setBorder(Border.ALL, BorderLineStyle.THIN); // 設定邊框
		
		// 設定表頭
		wsheet.setRowView(0, 500, false); // 設定行高
		wsheet.setColumnView(0, 20);// 設定列寬(25個字元寬)
		wsheet.setColumnView(1, 30);
		wsheet.setColumnView(2, 20);
		wsheet.addCell(new Label(0, 0, "卡單啟用結果", wcfFC));
		wsheet.addCell(new Label(0, 1, "agentCode", wcfFC));
		wsheet.addCell(new Label(1, 1, "卡號", wcfFC));
		wsheet.addCell(new Label(2, 1, "啟用狀態", wcfFC));
		
		// 合併單元格
		wsheet.mergeCells(0, 0, 2, 0);
		wfont = new WritableFont(WritableFont.ARIAL, 12, WritableFont.NO_BOLD, false, UnderlineStyle.NO_UNDERLINE);
		wcfFC = new WritableCellFormat(wfont);
		wcfFC.setAlignment(Alignment.CENTRE);// 把水平對齊方式指定為居中
		wcfFC.setVerticalAlignment(VerticalAlignment.CENTRE);// 把垂直對齊方式指定為居中
		wcfFC.setWrap(true);
		wcfFC.setBorder(Border.ALL, BorderLineStyle.THIN); // 設定邊框

		jxl.write.NumberFormat nf = new jxl.write.NumberFormat("#0.0##"); // 設定數字格式
		jxl.write.WritableCellFormat wcfN = new jxl.write.WritableCellFormat(nf); // 設定表單格式
		wcfN.setWrap(true);
		wcfN.setBorder(Border.ALL, BorderLineStyle.THIN); // 設定邊框
		wcfN.setFont(wfont);

		// 開始生成主體內容
		for (int i = 0; i < paramList.size(); i++) {
			Map<String, String> childMap = paramList.get(i);
			if (null == childMap || childMap.size() < 1) {
				continue;
			}
			String agentCode = childMap.get("agentCode");
			String certificationPrintNo = childMap.get("certificationPrintNo");
			String activeFlag = childMap.get("activeFlag");
			if ("0".equals(activeFlag)) {
				activeFlag = "未啟用";
			} else if ("1".equals(activeFlag)) {
				activeFlag = "已啟用";
			} else {
				activeFlag = "-";
			}
			wsheet.addCell(new Label(0, i + 2, agentCode != null ? agentCode : "-", wcfFC));
			wsheet.addCell(new Label(1, i + 2, certificationPrintNo, wcfFC));
			wsheet.addCell(new Label(2, i + 2, activeFlag, wcfFC));
		}
		
		// 主體內容生成結束
		wbook.write(); // 寫入檔案
	} catch (Exception e) {
		logger.error(e);
	} finally {
		try {
			if (wbook != null) {
				wbook.close();
			}
			if (out != null) {
				out.flush();
			    out.close();
			}
		} catch (Exception e) {
			logger.error(e);
		}
	}
}