我这里有个 word 文档,我想删除文档中包含 haha 这个字的页,该怎么写呢,word 如下
DeletePageTest.docx (15.7 KB)
@myboy 我认为在这种情况下,唯一的办法就是使用 LayoutCollector:
Document doc = new Document("DeletePageTest.docx");
// 指定要搜索的单词。
String wordToFind = "haha";
// 查找该词的所有出现次数。
ArrayList<Node> nodesToRemove = new ArrayList<>();
NodeCollection paragraphs = doc.getChildNodes(NodeType.PARAGRAPH, true);
for (Paragraph paragraph : (Iterable<Paragraph>) paragraphs) {
if (paragraph.getRange().getText().contains(wordToFind)) {
// 获取包含此段落的页面。
LayoutCollector layoutCollector = new LayoutCollector(doc);
int pageIndex = layoutCollector.getStartPageIndex(paragraph);
NodeCollection nodes = doc.getChildNodes(NodeType.ANY, true);
// 收集此页面上的所有节点。
for (Node node : (Iterable<Node>) nodes) {
if (layoutCollector.getStartPageIndex(node) == pageIndex) {
nodesToRemove.add(node);
}
}
}
}
// 从文档中删除节点。
for (Node node : nodesToRemove) {
node.remove();
}
doc.save("output.docx");
谢谢,感谢大佬提供的思路,成功解决了我的问题