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


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

操作Excel格式文件的HSSF和

用於操作Word的HWPF;

 

 

一、前端使用get請求和post請求都可以

get請求:

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

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

<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();

二、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插入表格;

 三、不需要插入表格:

 

 

XWPFTemplate template = XWPFTemplate.compile(templateFile).render(data);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM