gpt4 book ai didi

java - Apache POI : Extract a paragraph and the table that follows from word document (docx) in java

转载 作者:搜寻专家 更新时间:2023-10-31 20:00:36 24 4
gpt4 key购买 nike

我有一堆 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 (代码)我试过给出段落列表和表格列表,但不是按照我可以跟踪的顺序。

非常感谢任何帮助。

最佳答案

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
}
}

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

关于java - Apache POI : Extract a paragraph and the table that follows from word document (docx) in java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37599003/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com