如何使用Apache POI从MS word文档的文本框中获取文本?

问题描述 投票:1回答:3

我想从MS word文档的文本框中获取文本信息,我正在使用Apache POI来解析word文档。我正在使用Apache POI来解析word文档。

目前我正在遍历所有的段落对象,但这个段落列表并不包含TextBox的信息,所以我在输出中缺少这些信息。

例如

paragraph in plain text

**<some information in text box>**

one more paragraph in plain text

我想提取的是:

<para>paragraph in plain text</para>

<text_box>some information in text box</text_box>

<para>one more paragraph in plain text</para>

目前我得到的是:

纯文本段落

一段话

有谁知道如何使用Apache POI从文本框中提取信息?

ms-word document apache-poi
3个回答
3
投票

这对我来说是可行的。

    private void printContentsOfTextBox(XWPFParagraph paragraph) {

        XmlObject[] textBoxObjects =  paragraph.getCTP().selectPath("
            declare namespace w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' 
            declare namespace wps='http://schemas.microsoft.com/office/word/2010/wordprocessingShape' 
            declare namespace v='urn:schemas-microsoft-com:vml'
            .//*/wps:txbx/w:txbxContent | .//*/v:textbox/w:txbxContent");

        for (int i =0; i < textBoxObjects.length; i++) {
            XWPFParagraph embeddedPara = null;
            try {
            XmlObject[] paraObjects = textBoxObjects[i].
                selectChildren(
                new QName("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "p"));

            for (int j=0; j<paraObjects.length; j++) {
                embeddedPara = new XWPFParagraph(
                    CTP.Factory.parse(paraObjects[j].xmlText()), paragraph.getBody());
                //Here you have your paragraph; 
                System.out.println(embeddedPara.getText());
            } 

            } catch (XmlException e) {
            //handle
            }
        }

     } 

1
投票

从Word .doc和.docx文件中提取所有文本的出现,以便于 crgrep 我用的是 Apache Tika 源作为Apache POI APIs应该如何正确使用的参考。如果你想直接使用POI,而不是依赖Tika,这很有用。

对于Word .docx文件,可以看看这个Tika类。

org.apache.tika.parser.microsoft.ooxml.XWPFWordExtractorDecorator

如果你忽略了 XHTMLContentHandler 和格式化代码,你可以看到如何导航一个 XWPFDocument 正确使用POI.对于.doc文件来说,这个类很有帮助。

org.apache.tika.parser.microsoft.WordExtractor

无论是从 tika-parsers-1.x.jar. 通过你的maven依赖关系访问Tika代码的一个简单方法是将Tika临时添加到你的pom.xml中,如

<dependency>
    <groupId>org.apache.tika</groupId>
    <artifactId>tika-parsers</artifactId>
    <version>1.7</version>
</dependency>

让你的IDE解析附件中的源代码,然后进入上面的类。


0
投票

如果你想从docx文件的文本框中获取文本(使用 POI 3.10-FINAL)这里是示例代码。

FileInputStream fileInputStream = new FileInputStream(inputFile);
XWPFDocument document = new XWPFDocument(OPCPackage.open(fileInputStream)); 
for (XWPFParagraph xwpfParagraph : document.getParagraphs()) {
     String text = xwpfParagraph.getParagraphText(); //here is where you receive text from textbox
}

或者你可以遍历XWPFParagraph中的每个XWPFRun并调用toString()方法。同样的结果。

© www.soinside.com 2019 - 2024. All rights reserved.