当前位置: 首页 > article >正文

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

简介:

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


poi-tl官网文档 Poi-tl Documentation

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渲染不上。


http://www.kler.cn/a/369324.html

相关文章:

  • 如何成为一个优秀的大数据开发工程师?
  • Presto
  • 张驰咨询:六西格玛培训费用,到底值不值得花?
  • Mysql(十) --- 用户权限和管理
  • JVM(HotSpot):GC之G1垃圾回收器
  • Kaggle比赛复盘
  • 奥哲与中建三局集团有限公司战略签约
  • 美畅物联丨视频上云网关如何配置上级联网云平台
  • nacos安装与配置
  • 存储引用服务(OSS)Minio 环境搭建
  • 最新版的 Git+VS Code同步版本管理实践
  • 运维面试汇总
  • [JAVAEE] 面试题(一) - 锁策略, synchronized的详细介绍
  • 标题点击可跳转网页
  • 【32】C++流
  • ETLCloud+Doris组合:数据集成,更简单更高效
  • Linux系统基础-进程间通信(5)_模拟实现命名管道和共享内存
  • 【ubuntu18.04】ubuntu18.04 编译LightGBM操作说明
  • 大众点评 web mtgsig 1.2分析
  • AI跟踪报道第62期-本周AI新闻: 微软推出Copilot的AI Agent和Computer Control
  • 【学术会议投稿】Imagen:重塑图像生成领域的革命性突破
  • 深入理解Rust中的指针:裸指针 智能指针
  • Docker:容器
  • 2024 AI 时代:科学计算服务器——科技创新核心动力源
  • k8s 二进制部署安装(三)
  • 08 实战:色彩空间展示(本程序以视频为主)