Java 读取Word书签文本

2025-04-28 13:57:21

以下经验内容将分享通过Java编程来读取Word文档中书签所在位置的文本内容。

工具/原料

Free Spire.Doc for Java (免费版)

IntelliJ IDEA

jar文件获取及导入:

1、方法1:通过eiceblue官网下载jar文件包。下芙囹买乐载后,解压文件,并将lib文件夹下的Spire.Doc.jar文件导入java程序。参考如下导入效果:

Java 读取Word书签文本

2、方法2:可通过maven仓库安装导入到maven项目程序。

Java代码示例(供参考)

1、测试文档:

Java 读取Word书签文本

2、import com.spire.doc.*;import com.spire.doc.documents.BookmarksNavigator;import com.spire.doc.d泠贾高框ocuments.Paragraph;import com.spire.doc.documents.TextBodyPart;import com.spire.doc.fields.TextRange;import java.io.IOException;import java.io.PrintWriter;public class GetBookmarkText { public static void main(String[]args) throws IOException { //加载包含书签的Word文档 Document doc = new Document(); doc.loadFromFile("test.docx"); //获取书签 BookmarksNavigator bookmarksNavigator = new BookmarksNavigator(doc); bookmarksNavigator.moveToBookmark("bookmark1"); //获取书签文本 TextBodyPart textBodyPart = bookmarksNavigator.getBookmarkContent(); //创建String变量 String text = ""; //遍历书签内容的项目 for (Object item : textBodyPart.getBodyItems()) { //判断项目是否为段落 if (item instanceof Paragraph) { Paragraph paragraph = (Paragraph) item; //遍历段落中的子对象 for (Object childObj : paragraph.getChildObjects()) { //判断子对象是否为TextRange if (childObj instanceof TextRange) { //获取TextRange中的文本 TextRange textRange = (TextRange) childObj; text = text + textRange.getText(); } } } } //将获取到的文本写入Txt文件 PrintWriter printWriter = new PrintWriter("BookmarkText.txt"); printWriter.println(text); printWriter.close(); }}

3、书签文本读取结果:

Java 读取Word书签文本
声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢