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