java 实现对 word 文档中占位符进行替换

pom.xml

XML 复制代码
        <!-- Poi-tl Word 模板引擎-->
        <dependency>
            <groupId>com.deepoove</groupId>
            <artifactId>poi-tl</artifactId>
            <version>1.9.1</version>
        </dependency>

自己写一个word基础模版 然后需要替换的值用占位符{{name}}代替

代码

java 复制代码
package com.xgl.springboot.controller;

import com.deepoove.poi.XWPFTemplate;
import com.xgl.springboot.config.AppConfigManager;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

@RestController
public class FileController {

    @PostMapping("/convertFileToBase64")
    public ResponseEntity<?> convertFileToBase64(@RequestParam("file") MultipartFile file,
                                                 @RequestParam("params") HashMap<String, Object> params) throws IOException {
        
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body("File is empty");
        }
        
        // 将文件转换为 base64 字符串
        String base64String = Base64Utils.encodeToString(file.getBytes());
        
        // 处理其他参数 params
        // ...
        // 返回 base64 字符串和其他处理结果
        HashMap<String, Object> response = new HashMap<>();
        response.put("base64String", base64String);
        // ...
        
        return ResponseEntity.ok(response);
    }



    @PostMapping("/generate-doc")
    public String template(@RequestBody Map<String,Object> stringObjectMap){
        // 获取 Word 模板所在路径
        String filepath = "src/main/resources/template.docx";
        // 通过 XWPFTemplate 编译文件并渲染数据到模板中
        XWPFTemplate template = XWPFTemplate.compile(filepath).render(stringObjectMap);
        try {
            // 将完成数据渲染的文档写出
            template.writeAndClose(new FileOutputStream("src/main/resources/output.docx"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "success";
    }
}
相关推荐
鶴哥只手遮天4 小时前
Spring Framework 7.0.9 深度剖析-01-整体架构与设计哲学
java·后端·开源
const_qiu4 小时前
第 2.5 章 2.5.6:前端登录、Token 无感续签与路由守卫
java·前端·人工智能·状态模式
devilnumber4 小时前
Java 代理模式(简单理解回顾)
java·开发语言·代理模式
她的男孩4 小时前
Spring Boot 4 升级别只看编译绿:Forge Admin 在 Jackson、Tomcat JSON 限流、MP 包名与 Flowable 库上踩过的坑
java·spring boot·后端
Knight_AL4 小时前
别把 ThreadLocal 写进 Jackson Serializer
java·spring boot·spring
Song_RsHt4 小时前
Gateway (上):路由与转发,微服务的统一入口
java·笔记·后端·学习·gateway
paopaokaka_luck4 小时前
校园新闻推荐系统(DeepSeek新闻助手、个性化推荐算法、 Redis热词排行榜、ECharts运营分析、互动与实时通知、新闻运营闭环)
java·spring boot·mysql·spring·tomcat·echarts·intellij idea
yuniko-n4 小时前
【JUC】线程池
java·开发语言
小天源5 小时前
智叟云集政策监测技术方案——原文解析、证据提取与可核验摘要
java·服务器·数据库
凤山老林5 小时前
从零搭建企业 OAuth2 授权中心:Spring Boot 集成 Spring Authorization Server 与
数据库·spring boot·spring