Excel 格式報表生成 POI步驟
阿新 • • 發佈:2018-12-10
@Namespace("/") @ParentPackage("json-default") @Scope("prototype") @Controller public class ReportAction extends BaseAction<WayBill> { //自動注入wayBillService物件 @Autowired private WayBillService wayBillService; @Action(value="report_exportXls") public String exportXls() throws IOException { //查詢出滿足當前條件的結果資料,獲得需要轉化成表格的資料,該model是頁面傳來的資料自動封裝成的物件. //該部分邏輯不作介紹 List<WayBill> wayBills = wayBillService.findWayBills(model); //建立excel表格物件 HSSFWorkbook hssfWorkbook = new HSSFWorkbook(); HSSFSheet sheet = hssfWorkbook.createSheet("運單資料"); //建立表頭行 HSSFRow headRow = sheet.createRow(0); headRow.createCell(0).setCellValue("運輸單號"); headRow.createCell(1).setCellValue("寄件人姓名"); headRow.createCell(2).setCellValue("寄件人電話"); headRow.createCell(3).setCellValue("寄件人地址"); headRow.createCell(4).setCellValue("收件人姓名"); headRow.createCell(5).setCellValue("收件人電話"); headRow.createCell(6).setCellValue("收件人地址"); //每一次都迴圈建立資料列並對錶格資料進行遍歷插入 for (WayBill wayBill:wayBills ) { HSSFRow rows = sheet.createRow(sheet.getLastRowNum()+1); rows.createCell(0).setCellValue(wayBill.getWayBillNum()); rows.createCell(1).setCellValue(wayBill.getSendName()); rows.createCell(2).setCellValue(wayBill.getSendMobile()); rows.createCell(3).setCellValue(wayBill.getSendAddress()); rows.createCell(4).setCellValue(wayBill.getRecName()); rows.createCell(5).setCellValue(wayBill.getRecMobile()); rows.createCell(6).setCellValue(wayBill.getRecAddress()); } //下載匯出部分邏輯 //設定頭資訊,該ContentType是Excel固定格式 ServletActionContext.getResponse().setContentType("application/vnd.ms-excel"); //檔名 String filename = "運單資料.xls"; //從請求頭獲取瀏覽器型別 String agent = ServletActionContext.getRequest().getHeader("user-agent"); //使用工具類對檔名進行處理,使其不會亂碼 filename = FileUtils.encodeDownloadFilename(filename,agent); //設定檔名作為下載檔案的標識欄位 ServletActionContext.getResponse().setHeader( "Content-Disposition","attachment;filename="+filename); //獲取輸出流物件 ServletOutputStream servletOutputStream = ServletActionContext.getResponse().getOutputStream(); //輸出Excel表格 hssfWorkbook.write(servletOutputStream); //關閉 servletOutputStream.close(); return NONE; } }
附:FileUtils
/** * 下載檔案時,針對不同瀏覽器,進行附件名的編碼 * * @param filename * 下載檔名 * @param agent * 客戶端瀏覽器 * @return 編碼後的下載附件名 * @throws IOException */ public static String encodeDownloadFilename(String filename, String agent) throws IOException { if (agent.contains("Firefox")) { // 火狐瀏覽器 filename = "=?UTF-8?B?" + new BASE64Encoder().encode(filename.getBytes("utf-8")) + "?="; filename = filename.replaceAll("\r\n", ""); } else { // IE及其他瀏覽器 filename = URLEncoder.encode(filename, "utf-8"); filename = filename.replace("+"," "); } return filename; }