使用java替换MS word模板(Docx)中的文本
在Java中替换MS Word模板(.docx)中的文本,可以使用Apache POI库。Apache POI是一个强大的库,用于处理Microsoft Office文档,包括Word、Excel和PowerPoint。
1. 添加Apache POI依赖
如果你使用Maven构建工具,可以在pom.xml
文件中添加以下依赖:
<dependency> <groupId>com.deepoove</groupId> <artifactId>poi-tl</artifactId> <version>1.11.0</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>5.2.2</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>5.2.2</version> </dependency>
2. 编写Java代码
以下是一个示例代码,展示如何使用Apache POI库来替换Word模板中的文本:
import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.XWPFRun; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.List; public class WordTemplateReplacer { public static void main(String[] args) { String inputFilePath = "template.docx"; // 输入模板文件路径 String outputFilePath = "output.docx"; // 输出文件路径 try (FileInputStream fis = new FileInputStream(inputFilePath); XWPFDocument document = new XWPFDocument(fis)) { // 替换文本 replaceText(document, "${name}", "John Doe"); replaceText(document, "${date}", "2023-10-01"); // 保存修改后的文档 try (FileOutputStream fos = new FileOutputStream(outputFilePath)) { document.write(fos); } System.out.println("文档处理完成,已保存到 " + outputFilePath); } catch (IOException e) { e.printStackTrace(); } } private static void replaceText(XWPFDocument document, String searchText, String replacement) { for (XWPFParagraph paragraph : document.getParagraphs()) { List<XWPFRun> runs = paragraph.getRuns(); for (XWPFRun run : runs) { String text = run.getText(0); if (text != null && text.contains(searchText)) { text = text.replace(searchText, replacement); run.setText(text, 0); } } } } }
参考:https://cloud.tencent.com/developer/information/%E4%BD%BF%E7%94%A8java%E6%9B%BF%E6%8D%A2MS%20word%E6%A8%A1%E6%9D%BF(Docx)%E4%B8%AD%E7%9A%84%E6%96%87%E6%9C%AC-salon