我正在尝试从使用Apache poi XWPF生成的.docx文档中删除一个段落。我可以使用HWPF轻松地处理.doc word文档,如下所示:
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));
但不幸的是,没有达到我想要的结果。结果文档,我看不到段落被删除了。关于如何在XWPF中实现类似功能的任何建议。
发布于 2020-02-18 23:48:40
我喜欢Apache POI,而且在很大程度上它很棒,但至少可以说,我发现文档有点散乱。
难以捉摸的删除段落的方法,我发现这是一个噩梦,当我尝试删除一个段落时,给了我以下异常错误:
java.util.ConcurrentModificationException
正如在Ugo Delle Donne示例中提到的,我首先记录了我想要删除的段落,然后使用removeBodyElement方法处理文档,从而解决了这个问题。
例如:
List<XWPFParagraph> record = new ArrayList<XWPFParagraph>();
String text = "";
for (XWPFParagraph p : doc.getParagraphs()){
for (XWPFRun r : p.getRuns()){
text += r.text();
// I saw so many examples as r.getText(pos), don't use that
// Find some unique text in the paragraph
//
if (!(text==null) && (text.contains("SOME-UNIQUE-TEXT")) {
// Save the Paragraph to delete for later
record.add( p );
}
}
}
// Now delete the paragraph and anything within it.
for(int i=0; i< record.size(); i++)
{
// Remove the Paragraph and everything within it
doc.removeBodyElement(doc.getPosOfParagraph( record.get(i) ));
}// Shaaazam,我希望这对你有帮助!
https://stackoverflow.com/questions/29343921
复制相似问题