Apache POI 5.2.2 版本更新后的 Word 书签替换代码示例
package word;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBookmark;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class Word {
public static void main(String[] args) {
try {
// 打开输入文件input01.docx和input03.docx
FileInputStream input01 = new FileInputStream('input01.docx');
FileInputStream input03 = new FileInputStream('input03.docx');
XWPFDocument doc01 = new XWPFDocument(input01);
XWPFDocument doc03 = new XWPFDocument(input03);
// 获取input01.docx中应变计书签的内容
String bookmarkContent = getBookmarkContent(doc01, '应变计');
// 替换input03.docx中应变计书签的内容
replaceBookmarkContent(doc03, '应变计', bookmarkContent);
// 保存新文件input04.docx
FileOutputStream output = new FileOutputStream('input04.docx');
doc03.write(output);
output.close();
// 关闭文档
doc01.close();
doc03.close();
System.out.println('替换成功!');
} catch (Exception e) {
e.printStackTrace();
}
}
// 获取书签的内容
public static String getBookmarkContent(XWPFDocument doc, String bookmarkName) {
for (XWPFParagraph paragraph : doc.getParagraphs()) {
for (XWPFRun run : paragraph.getRuns()) {
for (CTBookmark bookmark : run.getCTR().getBookmarkStartList()) {
if (bookmark.getName().equals(bookmarkName)) {
return run.getText(0);
}
}
}
}
return null;
}
// 替换书签的内容
public static void replaceBookmarkContent(XWPFDocument doc, String bookmarkName, String content) {
for (XWPFParagraph paragraph : doc.getParagraphs()) {
for (XWPFRun run : paragraph.getRuns()) {
for (CTBookmark bookmark : run.getCTR().getBookmarkStartList()) {
if (bookmark.getName().equals(bookmarkName)) {
run.setText(content, 0);
}
}
}
}
}
}
在 Apache POI 版本 5.2.2 中,getBookmarkStartArray() 方法已被移除。取而代之的是 getBookmarkStartList() 方法。
代码示例说明:
- 引入必要的类: 导入
org.apache.poi.xwpf.usermodel包中的相关类,例如XWPFDocument,XWPFParagraph,XWPFRun, 以及org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBookmark类。 - 打开输入文件: 使用
FileInputStream类打开两个输入文件input01.docx和input03.docx。 - 创建 XWPFDocument 对象: 使用
XWPFDocument类创建两个 Word 文档对象doc01和doc03,分别对应输入文件。 - 获取书签内容: 使用
getBookmarkContent()方法获取input01.docx中名为 '应变计' 的书签内容。 - 替换书签内容: 使用
replaceBookmarkContent()方法将input03.docx中名为 '应变计' 的书签内容替换为获取到的内容。 - 保存新文件: 使用
FileOutputStream类创建一个输出文件input04.docx,并将修改后的doc03文档写入该文件。 - 关闭文档: 使用
close()方法关闭所有打开的文档和流。 - 打印成功信息: 打印一条消息,提示用户替换操作成功。
注意事项:
- 确保已将 Apache POI 库更新到版本 5.2.2 或更高版本。
- 确保
input01.docx和input03.docx文件存在于代码运行的目录中,并且input01.docx文件中包含名为 '应变计' 的书签。 - 替换书签的内容必须是有效的字符串。
代码实现:
getBookmarkContent()方法遍历文档的所有段落和运行,查找包含指定名称的书签,并返回该书签所在运行的文本内容。replaceBookmarkContent()方法遍历文档的所有段落和运行,查找包含指定名称的书签,并将该书签所在运行的文本内容替换为新的内容。
使用该代码示例,您可以轻松地实现 Word 文档中的书签替换操作,为您的工作带来极大的便利。
原文地址: https://www.cveoy.top/t/topic/fL9k 著作权归作者所有。请勿转载和采集!