poi-tl——Word模板生成器

学习目标

今天,和大家分享一款Word模板引擎,它可以基于Word模板和数据生成新的文档。在工作中我们经常会遇到,将后台的数据填充到特定的word模板中,然后生成渲染模板生成新的word提供下载;例如:学生成绩单,单位合同,报销费用等!如果能够掌控一款合适的java生成word模板的工具,将极大的提高我们的开发效率!


POI-tl介绍

poi-tl(poi template language)是Word模板引擎,基于Word模板和数据生成新的文档。
官方文档:http://deepoove.com/poi-tl

为什么我们选择poi-tl?
在这里插入图片描述
Apache POI不仅封装了易用的文档API(文本、图片、表格、页眉、页脚、图表等),也可以在底层直接操作文档XML结构,poi-tl正是一个基于Apache POI的Word模板引擎,并且拥有着让人喜悦的特性。

快速入门案例

1、添加依赖

<dependency>
       <groupId>com.deepoove</groupId>
       <artifactId>poi-tl</artifactId>
       <version>1.10.0</version>
</dependency>

2、主要代码

private static Logger logger = LoggerFactory.getLogger(FileUtils.class);
    /**
     *  渲染Word 文件
     * @param templatePath   文件模板路径
     * @param fileDir        生成文件的路径
     * @param fileName       生成的文件名
     * @param paramMap       数据
     * @return
     */
    public static String createWord(String templatePath, String fileDir, String fileName, Map<String, Object> paramMap) {
        File dir = new File(fileDir);
        if (!dir.exists()) {
            logger.info("目录不存在,创建文件夹{}!", fileDir);
            dir.mkdirs();
        }
        String filePath = fileDir +"/"+ fileName;
        XWPFTemplate template = XWPFTemplate.compile(templatePath).render(paramMap);
        try {
            template.writeToFile(filePath);
            template.close();
        } catch (Exception e) {
            logger.error("生成word异常{}", e.getMessage());
            e.printStackTrace();
        }
        return filePath;
    }

3、测试

public static void main(String[] args) throws Exception{
        String templatePath = "E:/template/template.docx";    //模板路径
        String fileDir = "E:/template/final/";  //生成文档路径
        String fileName = "output.docx";   //文件名
        Map<String,Object> params = new HashMap<>();
        params. put("title", "Hi, poi-tl Word模板引擎");
        String wordPath = FileUtils.createWord(templatePath, fileDir, fileName, params);
        System.out.println("生成文档的路径wordPath = " + wordPath);
    }

注:

  • 首先,我们把模板放在了E盘的template文件夹下面。模板里面的内容:
    在这里插入图片描述
  • 运行main方法,将会在E:\template\final生成最终的文件。在这里插入图片描述

渲染文本

准备word模板:
在这里插入图片描述

 public static void main(String[] args) throws Exception{
        String templatePath = "E:/template/template.docx";    //模板路径
        String fileDir = "E:/template/final/";  //生成文档路径
        String fileName = "output.docx";   //文件名
        Map<String,Object> params = new HashMap<>();
        params.put("dep","xxx部门");
        params.put("apply_man","张三");
        params.put("project","xxxxx项目费用");
        params.put("money","13000元");
        params.put("count","3");
        params.put("year","2021");
        params.put("month","03");
        params.put("day","23");
        String wordPath = FileUtils.createWord(templatePath, fileDir, fileName, params);
        System.out.println("生成文档的路径wordPath = " + wordPath);
    }

在这里插入图片描述

循环渲染

我们常常遇到,费用报销明细里面可能有多条记录,此时我们需要用到表格循环。

 public static void main(String[] args) throws Exception{
        String templatePath = "E:/template/template.docx";    //模板路径
        String fileDir = "E:/template/final/";  //生成文档路径
        String fileName = "output.docx";   //文件名
        HackLoopTableRenderPolicy policy = new HackLoopTableRenderPolicy();
        Money row01 = new Money();
        row01.setApply_man("张三");
        row01.setProject("xxxx项目费用");
        row01.setCount("1");
        row01.setMoney("2300");
        Money row02 = new Money();
        row02.setApply_man("李四");
        row02.setProject("xxxx项目费用");
        row02.setCount("4");
        row02.setMoney("6800");
        List<Money> moneys = new ArrayList<>();
        moneys.add(row01);
        moneys.add(row02);
        Configure config = Configure.builder()
                .bind("moneys", policy)
                .build();
        XWPFTemplate template = XWPFTemplate.compile(templatePath, config).render(
                new HashMap<String, Object>() {{
                    put("moneys", moneys);
                }}
        );
        template.writeToFile(fileDir+fileName);
        template.close();
    }

在这里插入图片描述

渲染图片

图片标签以@开始:{{@var}}

    public static void main(String[] args) throws Exception {
        Map<String, Object> params = new HashMap<>();
        String templatePath = "E:/template/template.docx";    //模板路径
        String imgPath = "E:/template/template-img.png";
        String fileDir = "E:/template/final/";

        params.put("img", Pictures.ofLocal(imgPath).size(567, 120).create());
        XWPFTemplate template = XWPFTemplate.compile(templatePath).render(params);
        template.writeToFile(fileDir + "output.docx");
        template.close();
    }

最终效果:
在这里插入图片描述


本篇文章到这里就基本结束了,如果这篇文章对你有帮助,希望大家能留下你的点赞、 关注、 分享、 留言❤️❤️❤️

在这里插入图片描述

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
当使用Poi-tl库根据Word模板填充内容生成Word文档时,可以使用Poi-tl提供的模板语法来处理空值。以下是一个示例代码: ```java import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFRun; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.ParagraphAlignment; import org.apache.poi.xwpf.usermodel.TextAlignment; import fr.opensagres.poi.xwpf.converter.pdf.PdfConverter; import fr.opensagres.poi.xwpf.converter.pdf.PdfOptions; import org.apache.poi.util.Units; import org.apache.poi.xwpf.usermodel.Document; import org.apache.poi.xwpf.usermodel.HeaderFooterType; import org.apache.poi.xwpf.usermodel.IBodyElement; import org.apache.poi.xwpf.usermodel.XWPFTable; import org.apache.poi.xwpf.usermodel.XWPFTableRow; import org.apache.poi.xwpf.usermodel.XWPFTableCell; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class WordTemplateFiller { public static void main(String[] args) { try { // 加载Word模板文件 FileInputStream templateStream = new FileInputStream("template.docx"); XWPFDocument document = new XWPFDocument(templateStream); // 填充内容 Map<String, Object> placeholders = new HashMap<>(); placeholders.put("name", "John Doe"); placeholders.put("age", "30"); placeholders.put("address", ""); replacePlaceholders(document, placeholders); // 保存填充后的文档 FileOutputStream outputStream = new FileOutputStream("filled_template.docx"); document.write(outputStream); outputStream.close(); System.out.println("Word文档生成成功!"); } catch (IOException e) { e.printStackTrace(); } } private static void replacePlaceholders(XWPFDocument document, Map<String, Object> placeholders) { for (XWPFParagraph paragraph : document.getParagraphs()) { for (XWPFRun run : paragraph.getRuns()) { String text = run.getText(0); if (text != null) { for (Map.Entry<String, Object> entry : placeholders.entrySet()) { String placeholder = "${" + entry.getKey() + "}"; if (text.contains(placeholder)) { Object value = entry.getValue(); if (value != null && !value.toString().isEmpty()) { text = text.replace(placeholder, value.toString()); } else { text = text.replace(placeholder, ""); // 替换为空字符串 } run.setText(text, 0); } } } } } } } ``` 在上述代码中,我们首先加载Word模板文件,然后定义了一个`placeholders`的映射,其中包含了要替换的占位符和对应的值。接下来,我们调用`replacePlaceholders`方法来替换文档中的占位符。 在`replacePlaceholders`方法中,我们遍历文档中的每个段落和文本运行,通过检查文本内容中是否包含占位符来确定是否需要替换。如果找到了匹配的占位符,则根据占位符对应的值来进行替换。如果值不为空且非空字符串,则将占位符替换为对应的值;如果值为空或空字符串,则将占位符替换为空字符串。 请注意,上述代码中使用的占位符格式为`${placeholder}`,你可以根据实际情况修改为其他格式。 以上是一个基本示例,你可以根据自己的需求进行修改和扩展。同时,需要确保在项目中添加了Poi-tl的依赖库。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小小Java开发者

“是一种鼓励,你懂的”

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值