数据导出生成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);
相关文章
相关标签/搜索