如何使用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屋!