Java如何使用Apache POI替换Microsoft Word文档中的文本?
下文笔者将讲述使用Apache POI替换Word文件中文本的方法及示例分享,如下所示
替换word文件中的文本,我们只需使用以下三种方法 1.openDocument() 打开word文件 2.replaceText() 替换文件中的内容 3.saveDocument() 保存文件例:Apache POI替换word文件中的内容
package com.java265.example.poi; import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.usermodel.CharacterRun; import org.apache.poi.hwpf.usermodel.Paragraph; import org.apache.poi.hwpf.usermodel.Range; import org.apache.poi.hwpf.usermodel.Section; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.URL; public class WordReplaceText { private static final String SOURCE_FILE = "test.doc"; private static final String OUTPUT_FILE = "new-test.doc"; public static void main(String[] args) throws Exception { WordReplaceText instance = new WordReplaceText(); HWPFDocument doc = instance.openDocument(SOURCE_FILE); if (doc != null) { doc = instance.replaceText(doc, "java265.com", "我是被替换后的文本"); instance.saveDocument(doc, OUTPUT_FILE); } } private HWPFDocument replaceText(HWPFDocument doc, String findText, String replaceText) { Range r = doc.getRange(); for (int i = 0; i < r.numSections(); ++i) { Section s = r.getSection(i); for (int j = 0; j < s.numParagraphs(); j++) { Paragraph p = s.getParagraph(j); for (int k = 0; k < p.numCharacterRuns(); k++) { CharacterRun run = p.getCharacterRun(k); String text = run.text(); if (text.contains(findText)) { run.replaceText(findText, replaceText); } } } } return doc; } private HWPFDocument openDocument(String file) throws Exception { URL res = getClass().getClassLoader().getResource(file); HWPFDocument document = null; if (res != null) { document = new HWPFDocument(new POIFSFileSystem( new File(res.getPath()))); } return document; } private void saveDocument(HWPFDocument doc, String file) { try (FileOutputStream out = new FileOutputStream(file)) { doc.write(out); } catch (IOException e) { e.printStackTrace(); } } }
注意事项: Maven依赖,可使用以下坐标信息 <!-- https://search.maven.org/remotecontent?filepath=org/apache/poi/poi/4.1.0/poi-4.1.0.jar --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.0</version> </dependency> <!-- https://search.maven.org/remotecontent?filepath=org/apache/poi/poi-scratchpad/4.1.0/poi-scratchpad-4.1.0.jar --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-scratchpad</artifactId> <version>4.1.0</version> </dependency>
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。