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";
    }
}
相关推荐
渴望技术的猿24 分钟前
Windows 本地部署MinerU详细教程
java·windows·python·mineru
diving deep26 分钟前
XML简要介绍
xml·java·后端
Uranus^28 分钟前
深入解析Spring Boot与Redis集成:高效缓存实践
java·spring boot·redis·缓存
小吕学编程30 分钟前
Jackson使用详解
java·javascript·数据库·json
椰椰椰耶31 分钟前
【RabbitMQ】整合 SpringBoot,实现工作队列、发布/订阅、路由和通配符模式
spring boot·rabbitmq·java-rabbitmq
总是难免1 小时前
设计模式 - 单例模式 - Tips
java·单例模式·设计模式
晚秋大魔王1 小时前
OpenHarmony 开源鸿蒙南向开发——linux下使用make交叉编译第三方库——wget
java·linux·运维·开发语言·华为·harmonyos
heath ceTide1 小时前
轻量、优雅、高扩展的事件驱动框架——Hibiscus-Signal
java·开发语言
_extraordinary_1 小时前
Java 常用的Arrays函数
java·开发语言
_extraordinary_1 小时前
Java 类和对象
java·开发语言