Java如何使用Apache POI替换Microsoft Word文档中的文本?
下面的代码段向您展示了如何使用Apache POI库替换Microsoft Word文档中的字符串。下面的类具有openDocument(),saveDocument()和replaceText()三种方法。
替换文本的例程在replaceText()方法中实现。此方法将HWPFDocument、要查找的字符串和替换它的字符串作为参数。openDocument()打开Word文档。文本替换完成后,Word文档将通过saveDocument()方法保存。
这是完整的代码片段。它将o用0源文档中的字符替换每个字符,lipsum.doc然后将结果保存到名为new-lipsum.doc的新文档中。
package org.nhooo.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 = "lipsum.doc";
private static final String OUTPUT_FILE = "new-lipsum.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, "o", "0");
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>
以上是 Java如何使用Apache POI替换Microsoft Word文档中的文本? 的全部内容, 来源链接: utcz.com/z/330302.html