一.引入相关jar
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
二.参考案例
public static void main(String[] args) {
try {
//获得word的pack对象
OPCPackage pack = POIXMLDocument.openPackage("files\\11.docx");
//获得XWPFDocument对象
XWPFDocument doc = new XWPFDocument(pack);
//输出doc body中包含的元素个数
System.out.println(doc.getBodyElements().size());
//输出pack中包含的的part个数,这里就是word文档的页数
System.out.println(pack.getParts().size());
//获得第一个段落对象
XWPFParagraph paragraph = doc.getParagraphs().get(0);
//段落的格式,下面及个设置,将使新添加的文字向左对其,无缩进.
paragraph.setIndentationLeft(0);
paragraph.setIndentationHanging(0);
paragraph.setAlignment(ParagraphAlignment.LEFT);
paragraph.setWordWrap(true);
//在段落中新插入一个run,这里的run我理解就是一个word文档需要显示的个体,里面可以放文字,参数0代表在段落的最前面插入
XWPFRun run = paragraph.insertNewRun(0);
//设置run内容
run.setText("finish");
run.setFontFamily("宋体");
run.setBold(true);
//因为不支持直接保存会原有对象,或者我不会,只能新保存一个文件,然后将原来的删除,将新的文件重命名回原文件名.
File oldFile = new File("files\\11.docx");
File newFile = new File("files\\22.docx");
FileOutputStream fos = new FileOutputStream(newFile);
doc.write(fos);
fos.flush();
fos.close();
pack.close();
System.out.println(oldFile.delete());
System.out.println(newFile.renameTo(oldFile));
} catch (Exception e) {
e.printStackTrace();
}
}
三.我的实现
public static void writerInPageHeading(String inputSrc, String outSrc) {
try {
XWPFDocument doc = new XWPFDocument(POIXMLDocument.openPackage(inputSrc));
//获得第一个段落对象
XWPFParagraph paragraph = doc.getParagraphs().get(0);
//在段落中新插入一个run,这里的run我理解就是一个word文档需要显示的个体,里面可以放文字,参数0代表在段落的最前面插入
XWPFRun r = paragraph.insertNewRun(0);
r.addBreak();//换行
r.setText("同意! CE2988/王五2 2019-02-20");
r.addBreak();
doc.write(new FileOutputStream(outSrc));
System.out.println("写入完成");
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException, InvalidFormatException {
//文件路径
String srcPath = "f:\\word\\needle.docx";
//替换后新文件的路径
String destPath = "f:\\word\\output.docx";
//插入内容
writerInPageHeading(srcPath,destPath);
}
结果: