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";
    }
}
相关推荐
Json_6 分钟前
学习springBoot框架-开发一个酒店管理系统,熟悉springboot框架语法~
java·spring boot·后端
kkkkk02110613 分钟前
微服务学习笔记(黑马商城)
java·spring boot·spring·spring cloud·sentinel·mybatis·java-rabbitmq
2503_9301239314 分钟前
Kubernetes (六)调度策略详解:从节点匹配到Pod调度全流程
java·开发语言
YBN娜29 分钟前
设计模式-创建型设计模式
java·开发语言·设计模式
桦说编程43 分钟前
CompletableFuture API 过于复杂?选取7个最常用的方法,解决95%的问题
java·后端·函数式编程
冲鸭ONE1 小时前
新手搭建Spring Boot项目
spring boot·后端·程序员
数智顾问1 小时前
Flink ProcessFunction 与低层级 Join 实战手册:多流广告计费精确去重
java·spring boot·spring
一头生产的驴1 小时前
java整合itext pdf实现固定模版pdf导出
java·python·pdf
魔都吴所谓1 小时前
【python】快速实现pdf批量去除指定位置水印
java·python·pdf
Camel卡蒙1 小时前
数据结构——字典树Trie(介绍、Java实现)
java·数据结构