數據導出生成word附件使用POI的XWPFTemplate對象

比較經常使用的實現Java導入、導出Excel的技術有兩種Jakarta POI和Java Excel。
Jakarta POI 是一套用於訪問微軟格式文檔的Java API。Jakarta POI有不少組件組成,其中有用於前端

操做Excel格式文件的HSSF和java

用於操做Word的HWPF;app

 

 

1、前端使用get請求和post請求均可以post

get請求:ui

window.location.href= appPath+"/export/handoverForm?ticketId="+self.ticketId +
                    "&complainId="+row.id+"&formCode="+self.exportFormCode.complainDetail;

隱藏form表單改寫成post請求,form表單get和post均可以:spa

<form id="exportForm" action="/service/xfComplain/exportCaseLedger" method="post">
        <input type="hidden" name="dataRange" id="dataRange"/>
        <input type="hidden" name="processStatus" id="processStatus"/>     
        <input type="hidden" name="cantonCode" id="cantonCode"/>
        <input type="hidden" name="startDate" id="startDate"/>
        <input type="hidden" name="endDate" id="endDate"/>
        <input type="hidden" name="multiFildMatch" id="multiFildMatch"/>
    </form>
$("#dataRange").val(self.table.pageData.dataRange); $("#processStatus").val(self.table.pageData.processStatus); $("#startDate").val(self.table.pageData.startDate); $("#endDate").val(self.table.pageData.endDate); $("#multiFildMatch").val(self.table.pageData.multiFildMatch); $('#exportForm').submit();

2、java代碼插件

@ResponseBody @RequestMapping("/exportWord") public void exportHandoverForm(HttpServletRequest request, HttpServletResponse response, ExportParam exportParam) { String projectPath = getProjectPath(request); String templateFile = getTemplateFile(exportParam, projectPath, request); Map<String, Object> data = new HashMap<>(); File file = null; InputStream in = null; ServletOutputStream out = null; try { // 數據源
            HandoverModel handoverModel = getHandoverFormData(exportParam.getComplainId()); // 反射機制,獲取全部屬性對象,在拿到屬性值,設置數據
            for (Field field : HandoverModel.class.getDeclaredFields()) { // 暴力反射,不是public修飾的屬性也要獲取
                field.setAccessible(true); data.put(field.getName(), field.get(handoverModel)); } // 數據源組成map鍵值對形式
            data.put("reportorList", handoverModel.getReportorList().getDatas()); String fileName = handoverModel.getCaseCode(); String exportFilePath = projectPath + ExportConstant.DEFAULT_EXPORT_PATH; logger.info("----------templateFile:" + templateFile); logger.info("-----------projectPath:" + projectPath); // Configure對象是處理表格數據,能夠自適應生成對應行數數據
            Configure config = Configure.newBuilder().customPolicy("reportorList", new FileTablePolicy()).build(); // XWPFTemplate對象是處理word文檔對象,根據map數據源的鍵值對渲染文檔數據
            XWPFTemplate template = XWPFTemplate.compile(templateFile, config).render(data); // 文件生成到本地,先生成好文檔,再讀取到內存中響應給前臺
            String downloadFileName = fileName + ".docx"; File outPutFile = new File(exportFilePath); if (!outPutFile.exists()) { outPutFile.mkdirs(); } FileOutputStream outFile = new FileOutputStream(exportFilePath + downloadFileName); template.write(outFile); outFile.flush(); outFile.close(); template.close(); // 經過文件流讀取到文件,再將文件經過response的輸出流,返回給頁面下載
            file = new File(projectPath + ExportConstant.DEFAULT_EXPORT_PATH + downloadFileName); in = new FileInputStream(file); response.setCharacterEncoding("utf-8"); response.setContentType("application/msword"); response.setHeader("Content-Disposition", "attachment;filename=" .concat(String.valueOf(URLEncoder.encode(downloadFileName, "UTF-8")))); out = response.getOutputStream(); byte[] buffer = new byte[512]; int bytesToRead = -1; // 用響應對象response中的輸出流讀取生成好的文件
            while ((bytesToRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesToRead); } } catch (Exception e) { logger.error("導出word出錯", e); } finally { if (in != null) try { in.close(); if (out != null) out.close(); if (file != null) file.delete(); // 刪除臨時文件
            } catch (IOException e) { logger.error("刪除刪除臨時文件出錯", e); } } }

使用XWPFTemplate引擎,插件化Configure插入表格;code

 3、不須要插入表格:orm

 

 

XWPFTemplate template = XWPFTemplate.compile(templateFile).render(data);
相關文章
相關標籤/搜索