You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 03:45:30