数据导出生成word附件使用POI的XWPFTemplate对象
生活随笔
收集整理的這篇文章主要介紹了
数据导出生成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);?
轉載于:https://www.cnblogs.com/wmqiang/p/11602884.html
總結
以上是生活随笔為你收集整理的数据导出生成word附件使用POI的XWPFTemplate对象的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: session案例之验证码
- 下一篇: ADO.NET,浅显