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";
    }
}
相关推荐
Grey Zeng4 小时前
Java SE 25新增特性
java·jdk·jdk新特性·jdk25
雨白5 小时前
Java 线程通信基础:interrupt、wait 和 notifyAll 详解
android·java
昵称为空C9 小时前
SpringBoot3 http接口调用新方式RestClient + @HttpExchange像使用Feign一样调用
spring boot·后端
架构师沉默9 小时前
设计多租户 SaaS 系统,如何做到数据隔离 & 资源配额?
java·后端·架构
Java中文社群10 小时前
重要:Java25正式发布(长期支持版)!
java·后端·面试
每天进步一点_JL11 小时前
JVM 类加载:双亲委派机制
java·后端
用户2986985301412 小时前
Java HTML 转 Word 完整指南
java·后端
渣哥12 小时前
原来公平锁和非公平锁差别这么大
java
渣哥12 小时前
99% 的人没搞懂:Semaphore 到底是干啥的?
java
J2K12 小时前
JDK都25了,你还没用过ZGC?那真得补补课了
java·jvm·后端