如何使用 XWPF 删除段落 - Apache POI [英] How to delete a paragraph using XWPF - Apache POI
问题描述
我正在尝试从我使用 Apache poi XWPF 生成的 .docx 文档中删除一个段落.我可以使用 HWPF 使用 .doc word 文档轻松完成,如下所示:
I am trying to delete a paragraph from the .docx document i have generated using the Apache poi XWPF. I can do it easily with the .doc word document using HWPF as below :
for (String paraCount : plcHoldrPargrafDletdLst) {
Paragraph ph = doc.getRange().getParagraph(Integer.parseInt(paraCount));
System.out.println("Deleted Paragraph Start & End: " + ph.getStartOffset() +" & " + ph.getEndOffset());
System.out.println("Deleted Paragraph Test: " + ph.text());
ph.delete();
}
我尝试对
doc.removeBodyElement(Integer.parseInt(paraCount));
doc.removeBodyElement(Integer.parseInt(paraCount));
但不幸的是没有成功到我想要的结果.结果文档,我看不到删除的段落.关于如何在 XWPF 中实现类似功能的任何建议.
But unfortunatley not successful enough to get the result as i want. The result document, i cannot see the paragraph deleted. Any suggestions on how to accompolish the similar functionality in XWPF.
推荐答案
好吧,这个问题有点老了,可能不再需要了,但我刚刚找到了一个与建议不同的解决方案.
Ok, this question is a bit old and might not be required anymore, but I just found a different solution than the suggested one.
希望以下代码能帮助遇到同样问题的人
Hope the following code will help somebody with the same issue
...
FileInputStream fis = new FileInputStream(fileName);
XWPFDocument doc = new XWPFDocument(fis);
fis.close();
// Find a paragraph with todelete text inside
XWPFParagraph toDelete = doc.getParagraphs().stream()
.filter(p -> StringUtils.equalsIgnoreCase("todelete", p.getParagraphText()))
.findFirst().orElse(null);
if (toDelete != null) {
doc.removeBodyElement(doc.getPosOfParagraph(toDelete));
OutputStream fos = new FileOutputStream(fileName);
doc.write(fos);
fos.close();
}
这篇关于如何使用 XWPF 删除段落 - Apache POI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!