POI中的Word API仍然处于不稳定状态,但是您应该能够通过以下两种方式之一迭代这些段落:
XWPFDocument doc = new XWPFDocument(fis);
List paragraphs = doc.getParagraphs();
for (XWPFParagraph p : paragraphs) {
... do something here
}
要么
XWPFDocument doc = new XWPFDocument(fis);
Iterator 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 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
}
}
这应该允许您按顺序遍历所有body元素.