1、创建模板文件
- 创建模板文件如format.docx,创建几个标题,并插入目录
- 将标题删除,只留目录
2、复制模板文件
private File copyFile(String tempPath, String targetPath) throws Exception {
File temp= new File(tempPath);
File target= new File(targetPath);
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream(temp);
out = new FileOutputStream(target);
byte[] buffer = new byte[1024];
while (in.read(buffer) != -1) {
out.write(buffer);
}
out.flush();
return target;
} finally {
in.close();
out.close();
}
}
3、打开word
/**
* 打开Word
*
* @param filePath 文件全路径
*/
public static XWPFDocument open(String filePath) throws Exception {
InputStream is = null;
try {
is = new FileInputStream(filePath);
return new XWPFDocument(is);
} finally {
is.close();
}
}
4、添加文档内容
public void setContent(XWPFDocument doc){
// 标题1,1级大纲
XWPFParagraph para1 = doc.createParagraph();
// 关键行// 1级大纲
para1.setStyle("1");
XWPFRun run1 = para1.createRun();
// 标题内容
run1.setText("标题1");
// 标题2,2级大纲
XWPFParagraph para2 = doc.createParagraph();
// 关键行// 2级大纲
para2.setStyle("2");
XWPFRun run2 = para2.createRun();
// 标题内容
run2.setText("标题2");
// 正文
XWPFParagraph paraX = doc.createParagraph();
XWPFRun runX = paraX.createRun();
for(int i=0;i<100;i++) {
// 正文内容
runX.setText("正文\r\n");
}
}
5、更新目录
public static void main(String[] args) {
String tempPath = "D:\\test\\poi\\word\\format.docx"; //模板文件路径
String targetPath = "D:\\test\\poi\\word\\test.docx";//生成文件路径
//复制模板
File file = copyFile(tempPath ,targetPath);
//打开word
XWPFDocument doc = open(targetPath);
//添加内容
setContent(doc);
//更新目录
doc.enforceUpdateFields();
//word写入到文件
FileOutputStream fos;
try {
fos = new FileOutputStream(targetPath);
doc.write(fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
6、结果展示
选择是