poi操作word文档docx

XWPF 文档(POI API 文档) (apache.org)

依赖

1
2
3
4
5
6
7
8
9
10
11
12
xml复制代码<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>

XWPFDocument类

1. 构造方法

  • XWPFDocument(java.io.InputStream is) 输入流读文件打开
1
java复制代码XWPFDocument document = new XWPFDocument(new FileInputStream(path));
  • XWPFDocument(OPCPackage pkg) 打开文档
1
java复制代码XWPFDocument document = new XWPFDocument(XWPFDocument.openPackage("C:\Users\admin\Desktop\0.docx"));

注意: 两种方式的区别 文件流打开

1
2
arduino复制代码 new XWPFDocument(new FileInputStream(path)) 打开操作word不会修改原模板输出操作时。
new XWPFDocument(XWPFDocument.openPackage("C:\Users\admin\Desktop\0.docx")) 原来的word模板会被修改

2.常用

  • createParagraph() 创建段落
  • createTable() 创建一个空表,其中一行和一列为默认值。也可以指定行列
  • createStyles() 如果文档尚未存在,则创建空样式
  • getParagraphs() 返回持有头或脚文本的段落。
  • insertNewParagraph(org.apache.xmlbeans.XmlCursor cursor) 在光标的位置添加新段落。 游标=光标
  • removeBodyElement(int pos)从word文档body元素阵列列表中删除身体元素(从上到下)
  • write(java.io.OutputStream out) 写文件

实例demo

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
java复制代码    public class Test004 {
public static void main(String[] args) throws IOException, OpenXML4JException, XmlException {

XWPFDocument document = new XWPFDocument(new FileInputStream("C:\Users\admin\Desktop\0.docx"));

XWPFParagraph paragraph = document.createParagraph();
//获取所有段落
List<XWPFParagraph> paragraphs = document.getParagraphs();
for (int i = 0; i < paragraphs.size(); i++) {
XWPFParagraph paragraph1 = paragraphs.get(i);
if (paragraph1.getText().equals("开头")){
//将一个新运行追加到这一段
XWPFRun r1=paragraph.createRun();
r1.addCarriageReturn();
// 获取当前光标位置
XmlCursor cursor = paragraph1.getCTP().newCursor();
cursor.toNextSibling();
// 光标位置插入新段落
XWPFParagraph newParagraph = document.insertNewParagraph(cursor);
XWPFRun run = newParagraph.createRun();
run.getCTR().addNewRPr().addNewHighlight().setVal(STHighlightColor.LIGHT_GRAY);
String s= " ";

String s1 = "插入当前位置!!!!";
StringBuilder stringBuilder = new StringBuilder();
for (int j = 0; j < 64-s1.length(); j++) {
stringBuilder.append(" ");
}
run.setText(s1+stringBuilder);


document.removeBodyElement(document.getPosOfParagraph(paragraph1));
}

System.out.println("死循环"+i);
}


document.write(new FileOutputStream("C:\Users\admin\Desktop\001.docx"));
document.close();

}
}
1
复制代码   效果

2F~RUEVDCQE4HJ}AT_GPO2I.png

本文转载自: 掘金

开发者博客 – 和开发相关的 这里全都有

0%