慢吞云雾缓吐愁 发表于 5 天前

Spring Boot 集成Poi-tl实现动态Word文档生成

Spring Boot 集成Poi-tl实现动态Word文档生成

「gen-pic-word.zip」
链接: https://pan.quark.cn/s/74396770a5c2
媒介

在项目开辟过程中,遇到了一个需求:将用户输入的数据填充到给定格式的 Word 文档中。简单来说,就是要根据预界说的模板生成一个新的 Word 文档,并自动填充数据。
什么是 Poi-tl?

   官网:http://deepoove.com/poi-tl/
poi-tl(Poi Template Language)是一个强大的 Word 模板引擎,可以或许根据 Word 模板和数据动态生成新的文档。底层是基于 Apache POI 实现的。
Apache POI 提供了轻便的 API 来操作各种 Word 文档元素(如文本、图片、表格、页眉、页脚、图表等),并允许直接操作文档的 XML 布局。
Poi-tl 的功能特点:

功能形貌文本渲染渲染模板中的文本标签图片渲染渲染模板中的图片标签表格渲染渲染模板中的表格标签列表渲染渲染模板中的列表标签图表渲染渲染差异范例的图表,包括柱状图、折线图等条件渲染根据条件显示或隐藏内容循环渲染对文本、图片、表格等内容进行循环渲染表格行/列循环对表格的行或列进行循环渲染图片更换更换文档中的指定图片超链接、书签、锚点支持文档内的超链接、书签、锚点等功能强大的表达式支持完全支持 SpringEL 表达式,并可扩展至 OGNL、MVEL 等表达式自界说标签支持支持自界说标签前后缀文本框支持支持文本框中的标签样式自界说自界说模板样式,同时代码中也可动态设置样式模板嵌套支持嵌套模板功能Word 合并支持 Word 中的合并操作自界说函数(插件)允许在模板中使用自界说函数 通过这些特性,我们可以轻松地实现模板渲染,生成符合特定格式要求的文档。
怎样使用 Poi-tl?

本文以 Spring Boot 项目为例,展示怎样集成 Poi-tl 进行模板渲染。小伙伴们可以按照步调一起实践!
1. 创建 Spring Boot 项目

起首,创建一个 Spring Boot 项目,版本为 2.2.1(可以根据需要调整版本)。在 pom.xml 文件中引入以下依靠:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
2. 添加 Poi-tl 依靠

接下来,向 pom.xml 中添加 Poi-tl 的依靠:
<dependency>
    <groupId>com.deepoove</groupId>
    <artifactId>poi-tl</artifactId>
    <version>1.9.1</version>
</dependency>
3. 预备 Word 模板

我们需要预备一个 Word 模板。可以手动创建一个 Word 文件,这里我们以 Hello World.docx 为例,模板内容如下:
https://i-blog.csdnimg.cn/img_convert/100b1b519afff7620b392e83194d1532.png
我们将模板存放在 resources 目录下,并界说几个占位符,例如:{{title}}、{{text}}、{{author}} 等。
4. 渲染模板并生成新文档

我们可以通过 XWPFTemplate 来渲染模板,将数据填充到模板中并生成新的文档。示例代码如下:
@SpringBootTest
public class PoiTlApplicationTest {
    @Test
    public void test() {
      // 获取 Word 模板路径
      String filepath = this.getClass().getClassLoader().getResource("hello-world.docx").getPath();

      // 渲染数据
      XWPFTemplate template = XWPFTemplate.compile(filepath).render(
            new HashMap<String, Object>() {{
                put("title", "Hello, poi-tl Word模板引擎");
                put("text", "Hello World");
            }}
      );

      // 输出新文档
      try {
            template.writeAndClose(new FileOutputStream("output.docx"));
      } catch (IOException e) {
            e.printStackTrace();
      }
    }
}
执行上述单位测试后,新的文档 output.docx 将会生成,而且内容将如预期渲染。
https://i-blog.csdnimg.cn/img_convert/5c6922f4b3c4c3b1b44da3ef7e567e1c.png
相干概念

模板

模板是一个 .docx 格式的文件,通常通过 Microsoft Word 或 WPS Office 创建。在模板中,我们使用占位符来标识需要动态渲染的内容。
标签

Poi-tl 使用标签来标识占位符,所有标签都以 {{ 开头,}} 结尾。标签可以出现在 Word 文档的任何位置,包括页眉、页脚、表格内部、文本框等。
数据模型

数据模型是将渲染数据传递给模板的方式,通常使用 Map 或 Java 对象。我们可以选择通过哈希表或对象来传递数据。

[*]哈希表(key 为标署名):
Map<String, Object> data = new HashMap<>();
data.put("title", "Hello, poi-tl Word模板引擎");
data.put("text", "Hello World");
data.put("author", "god23bin");
data.put("description", "这还不关注 god23bin?再不关注我可要求你关注了!");

[*]Java 对象(属性为标署名):
public class DataModel {
    private String title;
    private String text;
    private String author;
    private String description;
    // 省略 getter 和 setter
}

DataModel data = new DataModel();
data.setTitle("Hello, poi-tl Word模板引擎");
data.setText("Hello World");
data.setAuthor("god23bin");
data.setDescription("这还不关注 god23bin?再不关注我可要求你关注了!");
标签写法

Poi-tl 支持多种标签范例,常见的标签包括文本、图片、表格、列表等:


[*]文本标签:{{var}}
[*]图片标签:{{@var}}
[*]表格标签:{{#var}}
[*]列表标签:{{*var}}
插件

Poi-tl 支持插件机制,插件允许我们在模板中执行自界说的逻辑。例如,我们可以将 HTML 渲染插件绑定到某个标签上,使其支持 HTML 内容渲染。
Configure configure = Configure.builder().bind("description", new HtmlRenderPolicy()).build();
表格行循环

如果需要在 Word 文档中渲染多行表格数据,可以使用 HackLoopTableRenderPolicy 插件来循环渲染表格的行。
@Test
public void rowLoopTest() {
    AcWordModel data = getFromDB();// 假设从数据库获取数据
    String filepath = this.getClass().getClassLoader().getResource("table-row-loop.docx").getPath();
    Configure configure = Configure.builder()
      .bind("articles", new HackLoopTableRenderPolicy())
      .bind("columns", new HackLoopTableRenderPolicy())
      .build();
    XWPFTemplate template = XWPFTemplate.compile(filepath, configure).render(data);
    try {
      template.writeAndClose(new FileOutputStream("ac-word.docx"));
    } catch (IOException e) {
      e.printStackTrace();
    }
}
封装工具类

为了方便调用,我们可以封装一个工具类来处置惩罚 Word 渲染:
public class WordUtil {
    public static void generateWordFile(String templatePath, String targetPath, Map<String, Object> data) {
      XWPFTemplate template = XWPFTemplate.compile(templatePath).render(data);
      try {
            template.writeAndClose(new FileOutputStream(targetPath));
      } catch (IOException e) {
            e.printStackTrace();
      }
    }
}
总结

通过 Poi-tl,我们可以轻松实现基于模板的文档渲染。无论是简单的文本填充,还是复杂的表格、图表渲染,都能轻松应对。盼望这篇教程能帮助各人更好地使用 Poi-tl 进行文档自动化生成!

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: Spring Boot 集成Poi-tl实现动态Word文档生成