首页 > 其他分享 >SpringBoot poi-tl通过模板占位符生成word文件

SpringBoot poi-tl通过模板占位符生成word文件

时间:2024-10-24 10:19:40浏览次数:3  
标签:map word SpringBoot import tl poi put new HashMap

简介:

        开发中我们需要通过在word中使用占位符来动态渲染一些数据,本文讲解poi-tl实现动态生成word文档,包括表格循环,对象嵌套。


1. word格式

这是我的test.word

这是导出后的out.docx文件

2. 依赖

首先pom.xml导入依赖

		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi</artifactId>
			<version>5.2.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-ooxml</artifactId>
			<version>5.2.2</version>
		</dependency>
		<dependency>
			<groupId>com.deepoove</groupId>
			<artifactId>poi-tl</artifactId>
			<version>1.12.0</version>
		</dependency>

3. 实现代码

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class EditWordUtil {
    public static void main(String[] args) {
        String filePath = "D:/test.docx";

        try (FileInputStream resourceAsStream = new FileInputStream(new File(filePath));) {
            // 组装测试数据
            Map<String, Object> map = new HashMap<>();
            map.put("title", "日记");
            map.put("text", "好日子");
            map.put("score", 55);
            map.put("reward", "妈妈奖励我10块钱");
            map.put("imgUrl", "https://img2.baidu.com/it/u=485011689,3022056151&fm=253&fmt=auto&app=120&f=PNG?w=176&h=176");

            ArrayList<Map<String, Object>> list = new ArrayList<>();

            for (int i = 0; i < 4; i++) {
                HashMap<String, Object> maps = new HashMap<>();
                maps.put("name", "name" + i);
                maps.put("age", "age" + i);
                maps.put("address", "address" + i);
                list.add(maps);
            }
            map.put("lists", list);
            // 嵌套map数据
            HashMap<Object, Object> table = new HashMap<>();
            table.put("listTitle", "这是表格标题!");
            map.put("table", table);

            // 调用生成 Word 文件方法,将结果保存到本地
            EditWordUtil.createWordOfList("D:/out.docx", resourceAsStream, map);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    // 将生成的 Word 保存到本地文件系统
    public static boolean createWordOfList(String outputPath, InputStream templatePath, Map<String, Object> dates) throws IOException {
        try (FileOutputStream out = new FileOutputStream(outputPath);
             BufferedOutputStream bos = new BufferedOutputStream(out)) {

            // 使用Configure.ConfigureBuilder而不是Builder
            ConfigureBuilder builder = Configure.builder();
            LoopRowTableRenderPolicy loopRowTableRenderPolicy = new LoopRowTableRenderPolicy();

            // 动态绑定
            for (Map.Entry<String, Object> entry : dates.entrySet()) {
                if (entry.getValue() instanceof ArrayList) {
                    builder.bind(entry.getKey(), loopRowTableRenderPolicy);
                }
            }

            Configure configure = builder.build();

            // 读取模板并渲染数据
            XWPFTemplate template = XWPFTemplate.compile(templatePath, configure).render(dates);
            try {
                template.write(bos);
                template.close();
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }

            out.flush();
            bos.flush();
        }
        return true;
    }


小结:

普通对象字段使用 {{ }} 两个花括号包裹字段。

循环使用的是{{lists}},循环的内容是用中括号 [ ] 包裹的字段。

注意:{{ }}和[ ] 包裹字段的时候不能有空格,否则word渲染不上。

标签:map,word,SpringBoot,import,tl,poi,put,new,HashMap
From: https://blog.csdn.net/longshehui/article/details/143178811

相关文章

  • SpringBoot - poi-tl合并word文件表格,复杂word表格
    简介:    上篇文章说到开发中我们需要通过在word中使用占位符来动态渲染一些数据,    原文链接SpringBootpoi-tl通过模板占位符生成word文件-CSDN博客,        本文讲解poi-tl实现word表格之合并表格。1.word格式2.导出后的docx文件样式3.......
  • 【磐维数据库】WDR(Wordload Dignosis Report)报告
    WDR(WordloadDignosisReport)报告简介WDR报告是磐维数据库的工作负载诊断报告,它基于两个不同时间点系统的性能快照数据WDRSnapshot,生成这两个时间点之间的性能报告。WDRSnapshot的数据来源于DBE_PERFSchema内的视图。通过WDR报告,我们可以深入了解数据库在特定时间段内的运......
  • springboot校园论坛网站-毕业设计源码11401
    基于Java,web的校园论坛网站设计与实现摘 要基于Java语言和Springboot框架的校园论坛网站设计与实现,为校园内的师生提供了丰富的功能和便捷的服务。本论文旨在详细介绍该网站的设计思路、功能特点以及技术实现。论文介绍了网站的注册与登录功能,用户可以通过提供必要信息......
  • centos(linux): systemctl列出所有运行中/自启动的服务
    一,列出所有服务:systemctllist-units--type=service二,列出所有运行中的服务1,用--state指定状态systemctllist-units--type=service--state=running2,直接grepsystemctllist-units--type=service|greprunning三,列出所有自启动的服务1,列出所有自启动的单元......
  • 【C++篇】栈的层叠与队列的流动:在 STL 的韵律中探寻数据结构的优雅之舞
    文章目录C++栈与队列详解:基础与进阶应用前言第一章:栈的介绍与使用1.1栈的介绍1.2栈的使用1.2.1最小栈1.2.2示例与输出1.3栈的模拟实现第二章:队列的介绍与使用2.1队列的介绍2.2队列的使用2.2.1示例与输出2.3队列的模拟实现2.3.1示例与输出第三章:优先队......
  • 极狐GitLab 发布安全补丁版本17.3.3, 17.2.7, 17.1.8, 17.0.8, 16.11.10
    近期,极狐GitLab正式推出安全版本17.3.3,17.2.7,17.1.8,17.0.8,16.11.10,用来减缓安全漏洞CVE-2024-45409带来的安全风险。极狐GitLab正式推出针对GitLabCE老旧版本免费用户的GitLab专业升级服务,可以为老旧版本进行专业升级,避免业务宕机。漏洞详情标题严重等级C......
  • Matplotlib基础知识
    概念1.Matplotlib库:是一款用于数据可视化的Python软件包,支持跨平台运行,它能够根据NumPyndarray数组来绘制2D图像,它使用简单、代码清晰易懂2.Matplotlib图形组成:(1)Figure:指整个图形,您可以把它理解成一张画布,它包括了所有的元素,比如标题、轴线等(2)Axes:绘制2D图像的......
  • [快速阅读八] Matlab中bwlookup的实现及其在计算二值图像的欧拉数、面积及其他morph变
    以前看过matlab的bwlookup函数,但是总感觉有点神秘,一直没有去仔细分析,最近在分析计算二值图像的欧拉数时,发现自己写的代码和matlab的总是对不少,于是又去翻了下matlab的源代码,看到了matlab里实现欧拉数的代码非常简单,如下所示:ifn==4lut=4*[00.250.2500.250.5-......
  • Springboot知识点总结
    一、传统使用配置文件方式创建Java对象:1、创建一个普通的Maven项目,并加入依赖:<dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.3.1</version></dependency>&......
  • Java Springboot 接收前端上传图片,并返回路径让前端显示图片
    一、接收前端图片并保存并为前端返回一个图片路径. @RestController@RequestMapping("/upload")publicclassUploadImgController{@Autowired(required=false)privateResourceLoaderresourceLoader;@Value(value="/Users/user/Java/Upload/Serve......