Apache POI:从java中的word文档(docx)中提取段落和后续表格

Sau*_*hin 5 java docx apache-poi

我有一堆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)
Run Code Online (Sandbox Code Playgroud)

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

我尝试使用XWPFWordExtractor(读取所有文本),bodyElementIterator(迭代所有的body元素),但是大多数都提供getParagraphText()了一个方法,它给出了一个段落列表[para1, para2, para3, para4, para5]getTables()方法,它将文档中的所有表作为列表[table1, table2, table3, table4].

如何查看所有段落,停在标题"测试用例"(第4段)之后的段落,然后查找紧跟在第4段(表3)之后的表格.然后对第5段和第4段重复此操作.

这是我试过的主要链接(代码),它给出了一个段落列表和表格列表,但不是我能跟踪的顺序.

任何帮助深表感谢.

jma*_*phy 5

POI中的Word API仍在不断变化和存在bug,但是您应该能够通过以下两种方式之一遍历这些段落:

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

要么

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

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
   }
}
Run Code Online (Sandbox Code Playgroud)

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