【问题标题】:Apache POI: Extract a paragraph and the table that follows from word document (docx) in javaApache POI:从java中的word文档(docx)中提取段落和表格
【发布时间】:2016-10-02 14:42:03
【问题描述】:

我有一堆 word 文档 (docx),其中详细说明了测试用例名称作为段落标题以及后续表格中的测试步骤以及其他一些信息。

我需要使用 Apache POI 从表中提取测试用例名称(来自段落)和测试步骤(来自表)。

示例单词内容为

Section 1: Index
Section 2: Some description
    A. Paragraph 1
    B. Table 1
    C. Paragraph 2
    D. Paragraph 3
    E. Table 2
Section 3: test cases ( The title "test cases" is constant, so I can look for it in the doc)
    A. Paragraph 4 (First test case)
    B. Table 3 (Test steps table immediately after the para 4)
    C. Paragraph 5 (Second test case)
    B. Table 4 (Test steps table immediately after the para 5)

Apache POI 提供 API 来提供段落和表格列表,但我无法阅读段落(测试用例)并立即查找该段落后面的表格。

我尝试使用 XWPFWordExtractor(读取所有文本)、bodyElementIterator(遍历所有正文元素),但它们中的大多数都给出了getParagraphText() 方法,该方法给出了段落列表[para1, para2, para3, para4, para5]getTables() 方法给出了文档中的所有表格作为列表[table1, table2, table3, table4]

我如何遍历所有段落,停在标题“测试用例”之后的段落(第 4 段),然后查找紧随第 4 段之后的表格(表 3)。然后对第 5 段和表 4 重复此操作。

这是我试过的gist link(代码),它给出了段落列表和表格列表,但不是我可以跟踪的顺序。

非常感谢任何帮助。

【问题讨论】:

    标签: java apache-poi docx


    【解决方案1】:

    POI 中的 Word API 仍在不断变化,并且存在缺陷,但您应该能够通过以下两种方式之一对段落进行迭代:

    XWPFDocument doc = new XWPFDocument(fis);
    List<XWPFParagraph> paragraphs = doc.getParagraphs();
    for (XWPFParagraph p : paragraphs) {
       ... do something here
    }
    

    XWPFDocument doc = new XWPFDocument(fis);
    Iterator<XWPFParagraph> iter = doc.getParagraphsIterator();
    while (iter.hasNext()) {
       XWPFParagraph p = iter.next();
       ... do something here
    }
    

    Javadocs 说 XWPFDocument.getParagraphs() 检索在页眉或页脚中包含文本的段落,但我必须相信这是一个剪切和粘贴错误,因为 XWPFHeaderFooter.getParagraphs() 也说了同样的话。查看源代码,XWPFDocument.getParagraphs() 返回一个不可修改的列表,而使用迭代器使段落可修改。这可能会在未来发生变化,但它是目前的工作方式。

    要检索所有正文元素、段落和表格的列表,您需要使用:

    XWPFDocument doc = new XWPFDocument(fis);
    Iterator<IBodyElement> iter = doc.getBodyElementsIterator();
    while (iter.hasNext()) {
       IBodyElement elem = iter.next();
       if (elem instanceof XWPFParagraph) {
          ... do something here
       } else if (elem instanceof XWPFTable) {
          ... do something here
       }
    }
    

    这应该允许您按顺序遍历所有正文元素。

    【讨论】:

    • 感谢 cmets,我主要关心的是,段落列表给出了段落列表,表格列表给出了表格列表,但我如何跟踪它们出现的顺序?我的要求是提取紧跟在特定段落内容之后的表格内容。一些我必须如何继续阅读 paras 以及当我需要的 para 出现时,从那时起停止并开始阅读表格。
    • @Sauchin 你明白了吗?我也有同样的问题。如果您有解决方案,也许可以发布您自己的答案
    • 我确实找到了解决方案。我很抱歉没有早点发帖。我将在几天后发布答案。我正在旅行,不幸的是无法访问源代码。
    • @SebastianZeki - 答案在 6 月 5 日的上述编辑中。请注意,XWPFDocument 中有一个 bodyElements 列表,其中包含按顺序排列的所有段落和表格。
    • @Sauchin 我还是想看看你的解决方案。
    【解决方案2】:

    我能想到的唯一解决方案是使用单词提取器,将来自该提取器的段落内容与XWPFDocumentgetParagraphArray 进行比较,然后通过比较来自提取器和getTables() 的内容来定位表格。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-28
      • 2016-10-29
      • 1970-01-01
      相关资源
      最近更新 更多