Springboot项目中使用Word模板替换占位符生成新文件

🍁 作者:知识浅谈,CSDN签约讲师,CSDN博客专家,华为云云享专家,阿里云专家博主
📌 擅长领域:全栈工程师、爬虫、ACM算法,大数据,深度学习
💒 公众号:知识浅谈
🔥 微信:zsqtcyl 联系我领取福利

🤞Springboot项目中使用Word模板替换占位符生成新文件🤞

🎈前言

在Spring Boot项目中制作Word模板并替换模板中的内容,通常会用到Apache POI库,这是一个强大的Java库,可以用来处理Microsoft Office文档,包括Word、Excel等。以下是一个简单的步骤说明,展示如何使用Apache POI在Spring Boot项目中替换Word模板(.docx)中的内容。

如果 Word 模板中的占位符格式是 ${placeholder}(例如 ${name} 和 ${date}),你可以通过以下步骤来处理模板替换:

  • 加载模板:读取 Word 模板文件。
  • 替换占位符:用给定的值替换占位符。
  • 处理未被替换的占位符:用空字符串替换那些未被替换的占位符。

🎈添加依赖

确保在 pom.xml 中包含 Apache POI 的依赖项:

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>5.2.3</version>
</dependency>

🎈新建DocumentService 类

在 DocumentService 类中,使用 ${} 格式的占位符来进行替换:

import org.apache.poi.xwpf.usermodel.*;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.Map;

public class DocumentUtil {

    public static ByteArrayInputStream generateDocument(Map<String, String> replacements) throws IOException {
        // Load template from resources
        ClassPathResource resource = new ClassPathResource("templates/template.docx");
        try (InputStream templateStream = resource.getInputStream();
             XWPFDocument document = new XWPFDocument(templateStream)) {

            // Replace placeholders in paragraphs
            for (XWPFParagraph paragraph : document.getParagraphs()) {
                replaceText(paragraph, replacements);
            }

            // Replace placeholders in tables
            for (XWPFTable table : document.getTables()) {
                for (XWPFTableRow row : table.getRows()) {
                    for (XWPFTableCell cell : row.getTableCells()) {
                        for (XWPFParagraph paragraph : cell.getParagraphs()) {
                            replaceText(paragraph, replacements);
                        }
                    }
                }
            }

            // Write document to ByteArrayOutputStream
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            document.write(out);
            return new ByteArrayInputStream(out.toByteArray());
        }
    }

    private static  void replaceText(XWPFParagraph paragraph, Map<String, String> replacements) {
        for (XWPFRun run : paragraph.getRuns()) {
            String text = run.getText(0);
            if (text != null) {
                for (Map.Entry<String, String> entry : replacements.entrySet()) {
                    text = text.replace("${" + entry.getKey() + "}", entry.getValue());
                }
                // Replace remaining placeholders with empty string
                for (String key : replacements.keySet()) {
                    text = text.replace("${" + key + "}", ""); // Replace unmatched placeholders
                }
                run.setText(text, 0);
            }
        }
    }
}

🎈创建控制器

创建一个控制器来提供生成的文档

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Map;

@RestController
public class DocumentController {

    @Autowired
    private DocumentService documentService;

    @GetMapping("/generateDocx")
    public ResponseEntity<ByteArrayInputStream> generateDocx(@RequestParam Map<String, String> replacements) {
        try {
            ByteArrayInputStream bais = documentService.generateDocument(replacements);

            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=generated.docx");

            return new ResponseEntity<>(bais, headers, HttpStatus.OK);
        } catch (IOException e) {
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}

🎈测试

启动你的 Spring Boot 应用,并访问 http://localhost:8080/generateDocx?name=John&date=2024-08-30,将会生成并下载替换了占位符的 Word 文档。

这个方法将确保 Word 文档中的 ${} 格式占位符得到正确处理,如果某些占位符在 replacements 中没有对应的替换值,它们会被替换为空字符串。

🍚总结

大功告成,撒花致谢🎆🎇🌟,关注我不迷路,带你起飞带你富。
Writted By 知识浅谈

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

知识浅谈

您的支持将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值