Poi-tl

Poi-tl导出word模板

poi-ti是什么

poi-tl是一个Word 模板引擎,基于Apache poi,目标是在文档的任何地方做任何事情。具体详情可以查看官网信息。poi-tl

项目开发中使用

  1. 为什么要使用poi-tl
    原因很简单就是简单方便,避免了之前poi存在的很多兼容问题和繁琐处理逻辑
  2. 引入maven至项目(或者下载对应的jar包添加至项目的lib目录下)maven和jar包地址
  3. 快速入门
    新建文档template.docx,包含文本在word中添加并将文本中所要替换的部分改用{{title}}
//核心API采用了极简设计,只需要一行代码
XWPFTemplate.compile("template.docx").render(new HashMap<String, Object>(){{
        put("title", "Poi-tl 模板引擎");
}}).writeToFile("out_template.docx");
  1. 下图为使用的标签在这里插入图片描述

具体文档可以参考poi-tl的github网站 https://github.com/Sayi/poi-tl

实例代码(页面导出word)

页面点击下载导出word模板

@RequestMapping(value = "/exportWordFile", method = RequestMethod.GET)
    public void exportWordFile(HttpServletRequest request,HttpServletResponse response, String queryDate) {
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("ppdm", "关于北京辖区上市公司情况的谈参");
        data.put("ppdmContain", "20191219");
        data.put("pubCompCnt", "19");
        data.put("photo", new PictureRenderData(1000, 1200, "D:/usr/test.jpg"));// 本地图片
        File file = null;
        InputStream in = null;
        ServletOutputStream out = null;
            String wordName = "test.docx";
            String projectPath = request.getSession().getServletContext().getRealPath("/");
            String exportFilePath = projectPath+ "WEB-INF/ExcelModel/";
            String templateFile = exportFilePath+wordName;
            logger.info("----------templateFile:{}", templateFile);
            // Configure对象是处理表格数据,可以自适应生成对应行数数据
//            Configure config = Configure.newBuilder().build();
            // XWPFTemplate对象是处理word文档对象,根据map数据源的键值对渲染文档数据
            XWPFTemplate template = XWPFTemplate.compile(templateFile).render(data);
            // 文件生成到本地,先生成好文档,再读取到内存中响应给前台
            String downloadFileName = "公司治理专项自查统计报告_" +  queryDate+ ".docx";
            try {
                FileOutputStream outFile = new FileOutputStream(exportFilePath + downloadFileName);
                template.write(outFile);
                outFile.flush();
                outFile.close();
                template.close();
            } catch (Exception e) {
                logger.error("替换文件失败-关闭流失败!", e);
            }
            // 通过文件流读取到文件,再将文件通过response的输出流,返回给页面下载
            file = new File(exportFilePath + downloadFileName);
            try {
                in = new FileInputStream(file);
                response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
                response.setContentType("application/msword");
                response.setHeader("Content-Disposition", "attachment;filename=".concat(String.valueOf(URLEncoder.encode(downloadFileName, StandardCharsets.UTF_8.toString()))));
                out = response.getOutputStream();
                byte[] buffer = new byte[512];
                int bytesToRead = -1;
                // 用响应对象response中的输出流读取生成好的文件
                while ((bytesToRead = in.read(buffer)) != -1) {
                    out.write(buffer, 0, bytesToRead);
                }
//                Files.copy(Paths.get(file.getPath()),out);
            } catch (Exception e) {
                logger.error("读取替换后文件失败!", e);
            }finally {
                if (in != null) try {
                    in.close();
                    if (out != null) out.close();
                    if (file != null) file.delete(); // 删除临时文件
                } catch (IOException e) {
                    logger.error("删除临时文件出错", e);
                }
            }
    }

实例代码中的word模板已上传,仅供参考!其中模板位置可以根据自己项目制定存放。


版权声明:本文为princejwg原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。