🍁 作者:知识浅谈,CSDN签约讲师,CSDN博客专家,华为云云享专家,阿里云专家博主 📌 擅长领域:全栈工程师、爬虫、ACM算法 🔥 公众号:知识浅谈 联系我领取学习资料

(🤞Spring Boot 替换Word模板生成Word文件教程 🤞)

在Spring Boot项目中,替换Word模板并生成新的Word文件是一个常见的需求。这通常涉及到读取一个预定义的Word模板(.docx),替换其中的占位符,然后保存为新的Word文件。以下是一个详细的教程,展示了如何使用Apache POI库来完成这个任务。

🎈添加依赖

首先,你需要在你的Spring Boot项目的pom.xml文件中添加Apache POI的依赖。Apache POI是一个流行的Java库,用于处理Microsoft Office文档。

<dependencies>
    <!-- Apache POI for Word processing -->
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>5.2.3</version>
    </dependency>
    <!-- Optional: Spring Boot Starter Web if you need to expose an API -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

🎈创建Word模板

在你的项目中创建一个Word模板(例如template.docx),并在其中使用占位符,例如${name}、${date}等。这些占位符将在生成文件时被实际数据替换。

🎈编写服务类

接下来,你需要编写一个服务类来读取模板、替换占位符并生成新的Word文件。以下是一个简单的服务类示例:

import org.apache.poi.xwpf.usermodel.*;
import .ClassPathResource;
import java.io.*;
import java.util.Map;

public class WordDocumentService {

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

            // 替换段落中的占位符
            for (XWPFParagraph paragraph : document.getParagraphs()) {
                replaceTextInParagraph(paragraph, replacements);
            }

            // 替换表格中的占位符
            for (XWPFTable table : document.getTables()) {
                for (XWPFTableRow row : table.getRows()) {
                    for (XWPFTableCell cell : row.getTableCells()) {
                        for (XWPFParagraph paragraph : cell.getParagraphs()) {
                            replaceTextInParagraph(paragraph, replacements);
                        }
                    }
                }
            }

            // 将文档写入到ByteArrayOutputStream
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            document.write(out);
            return new ByteArrayInputStream(out.toByteArray());
        }
    }

    private void replaceTextInParagraph(XWPFParagraph paragraph, Map<String, String> replacements) {
        for (XWPFRun run : paragraph.getRuns()) {
            String text = run.getText(0);
            if (text != null) {
                StringBuilder sb = new StringBuilder(text);
                for (Map.Entry<String, String> entry : replacements.entrySet()) {
                    String placeholder = "${" + entry.getKey() + "}";
                    int index = sb.indexOf(placeholder);
                    while (index != -1) {
                        sb.replace(index, index + placeholder.length(), entry.getValue());
                        index = sb.indexOf(placeholder, index + entry.getValue().length());
                    }
                }
                run.setText(sb.toString(), 0);
            }
        }
    }
}

🎈创建控制器(可选)

如果你需要通过Web接口来触发文档生成,你可以创建一个控制器类。以下是一个简单的示例:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

@RestController
@RequestMapping("/api/word")
public class WordDocumentController {

    @Autowired
    private WordDocumentService wordDocumentService;

    @GetMapping("/generate")
    public void generateDocument() throws IOException {
        Map<String, String> replacements = new HashMap<>();
        replacements.put("name", "张三");
        replacements.put("date", "2023-10-01");

        ByteArrayInputStream documentStream = wordDocumentService.generateDocument(replacements);

        // 这里仅作为示例,实际中你可能需要将文档流发送到客户端进行下载
        // 以下代码仅为演示如何可能处理流,具体实现会依赖于你的需求
        // 例如,你可以使用Spring MVC的ResponseEntity来发送文件流

        // 假设这是一个不完整的示例,仅为了说明方向
        // 在实际项目中,你可能需要处理HTTP响应头,如设置Content-Type和Content-Disposition
        // 下面是一个简化的伪代码片段,用于说明如何可能返回文件流

        // 伪代码:
        // ResponseEntity<Resource> response = ResponseEntity
        //     .ok()
        //     .header("Content-Disposition", "attachment; filename=\"generated_document.docx\"")
        //     .contentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.wordprocessingml.document"))
        //     .body(new InputStreamResource(documentStream));

        // 注意:上面的伪代码没有实际运行,因为`ByteArrayInputStream`不是`InputStreamResource`的直接来源
        // 你可能需要使用`ByteArrayResource`或类似的方式,并确保流在发送后不会被关闭

        // 在实际项目中,你应该使用Spring MVC的功能来正确设置响应头和返回文件流

        // 由于篇幅和上下文限制,这里不再深入展开具体的控制器实现
        // 你可以查阅Spring Boot和Spring MVC的文档,了解如何创建文件下载接口

        // 注意:在上面的伪代码中,我们没有真正关闭`documentStream`,因为在实际应用中,
        // Spring MVC会负责关闭与客户端连接相关的资源。然而,在处理流时,请务必注意资源管理,
        // 避免内存泄漏和其他潜在问题。
    }
}

🎈测试

现在,你可以运行你的Spring Boot应用程序,并通过调用/api/word/generate端点来测试Word文档的生成。由于我们在示例中没有实现完整的文件下载逻辑,你可能需要根据你的具体需求来完成这部分。

🍚总结

本教程展示了如何在Spring Boot应用程序中使用Apache POI库来读取Word模板、替换占位符并生成新的Word文件。你可以根据需要调整服务类和控制器类,以满足你的具体需求。注意,处理文件流和设置HTTP响应头时,请确保你遵循了最佳实践,以避免资源泄漏和其他潜在问题。 大功告成,撒花致谢🎆🎇🌟,关注我不迷路,带你起飞带你富。 作者:码海浮生