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";
    }
}
相关推荐
追随者永远是胜利者5 小时前
(LeetCode-Hot100)253. 会议室 II
java·算法·leetcode·go
追随者永远是胜利者6 小时前
(LeetCode-Hot100)207. 课程表
java·算法·leetcode·go
yanghuashuiyue7 小时前
lambda+sealed+record
java·开发语言
盟接之桥8 小时前
盟接之桥EDI软件:API数据采集模块深度解析,打造企业数据协同新引擎
java·运维·服务器·网络·数据库·人工智能·制造
HoneyMoose8 小时前
Spring Boot 2.4 部署你的第一个 Spring Boot 应用需要的环境
java
rfidunion8 小时前
springboot+VUE+部署(12。Nginx和前端配置遇到的问题)
前端·vue.js·spring boot
皮皮林5518 小时前
为什么 Spring 和 IDEA 都不推荐使用 @Autowired 注解??
java
衍生星球9 小时前
【JSP程序设计】Servlet对象 — page对象
java·开发语言·servlet·jsp·jsp程序设计
vx-Biye_Design9 小时前
servlet家政公司管理系统-计算机毕业设计源码01438
java·vue.js·spring·servlet·tomcat·maven·mybatis
云和数据.ChenGuang9 小时前
jenkins安装需要多少版本的jdk
java·servlet·jenkins