如何使用Apache POI删除DOCX文档中的指定行?
如何用Apache POI彻底删除DOCX中的指定段落(行)
你当前的代码只是清空了段落内的文本内容,但段落对象本身仍然存在,所以会留下空行。要彻底删除该行,需要直接移除对应的XWPFParagraph对象,而不是仅清空内容。
注意:不能在遍历doc.getParagraphs()的过程中直接删除段落,否则会抛出ConcurrentModificationException。正确的做法是先收集所有需要删除的段落,再批量移除。
修改后的代码如下:
XWPFDocument doc = new XWPFDocument(OPCPackage.open(templatesPath + templateName)); // 先收集所有需要删除的段落 List<XWPFParagraph> paragraphsToDelete = new ArrayList<>(); for (XWPFParagraph p : doc.getParagraphs()) { String line = p.getText(); if (line != null && line.contains("@@THE_LINE_WILL_BE_DELETED@@")) { paragraphsToDelete.add(p); } } // 批量移除目标段落 for (XWPFParagraph p : paragraphsToDelete) { doc.getDocument().getBody().removeParagraph(p); } // 记得最后保存文档 try (FileOutputStream out = new FileOutputStream("output.docx")) { doc.write(out); } catch (IOException e) { e.printStackTrace(); }
关键说明
- 先遍历并收集需要删除的段落,避免在遍历原集合时修改结构导致异常。
- 通过
doc.getDocument().getBody().removeParagraph(p)直接从文档的XML结构中移除段落节点,这才是彻底删除段落的核心操作,而非仅清空文本。
内容的提问来源于stack exchange,提问作者sretkaya
相关产品推荐
相关产品推荐

