首先需要对应的依赖

1
2
3
4
5
6
7
8
9
10
11
12
<dependencies>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.16</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.3.2</version>
</dependency>
</dependencies>

示例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/**
* 段落删除
*
* @author chenghao.li
*/
public class ParagraphExample {
public static void main(String[] args) {
List<String> keywords = new ArrayList<>();
keywords.add("测试");
deleteParagraphByKeyWords("D:\\3.docx", keywords);
}

/**
* 删除包含指定关键字的段落
*
* @param path 目标文件路径
* @param keywords 关键字
*/
public static void deleteParagraphByKeyWords(String path, List<String> keywords) {
FileInputStream fis = null;
OutputStream fos = null;
try {
// 读取文档
fis = new FileInputStream(path);
XWPFDocument doc = new XWPFDocument(OPCPackage.open(fis));
// 拿到所有段落
List<XWPFParagraph> paragraphs = doc.getParagraphs();
// 根据关键字收集到需要删除的段落
List<XWPFParagraph> deleteList = new ArrayList<>();
for (XWPFParagraph paragraph : paragraphs) {
String text = paragraph.getText();
for (String keyword : keywords) {
if (text.contains(keyword)) {
deleteList.add(paragraph);
}
}
}
// 执行段落的删除
if (!deleteList.isEmpty()) {
for (XWPFParagraph xwpfParagraph : deleteList) {
doc.removeBodyElement(doc.getPosOfParagraph(xwpfParagraph));
}
}
// 覆盖历史文档
fos = new FileOutputStream(path);
doc.write(fos);
fos.close();
} catch (Exception e) {
System.out.println(Arrays.toString(e.getStackTrace()));
} finally {
try {
if (fis != null) {
fis.close();
}
if (fos != null) {
fos.close();
}
} catch (IOException e) {
System.out.println(Arrays.toString(e.getStackTrace()));
}
}
}
}

效果:会把整个段落删除,如果有自动编号的话,也会自动调整

测试文件:

删除后的效果: