一、模版插入占位符,生成文档时自动生成页码。
1.在word模板里新增页脚。
2.直接在模版第一页输入“第 1 页共1页”。
3.选中“第 1 页共1页”按住“Alt+F9”,自动解析为代码块第{ PAGE \\* MERGEFORMAT} 页 共 {NUMPAGES \\* MERGEFORMAT} 页
如果不能解析,则直接在页脚处输入
第{ PAGE \\* MERGEFORMAT} 页 共 {NUMPAGES \\* MERGEFORMAT} 页
或者
第{ PAGE \\* MERGEFORMAT} 页
具体看需要的样式,是否需要总页码
4.使用代码生成word后,页码会随着内容的增多自动更新
二、 使用代码,在生成word时直接插入页脚并设置页码
//填充主模版数据
XWPFTemplate template = XWPFTemplate.compile(downloadZhu, builder.build()).render(generate);
log.info("===============主模板生成完成================");
NiceXWPFDocument xwpfDocument = template.getXWPFDocument();
// 假设 xwpfDocument 是你已经生成的文档对象
XWPFHeaderFooterPolicy headerFooterPolicy = new XWPFHeaderFooterPolicy(xwpfDocument);
// 创建新的页脚段落
XWPFParagraph footerParagraph = new XWPFParagraph(CTP.Factory.newInstance(), xwpfDocument);
footerParagraph.setAlignment(ParagraphAlignment.CENTER);
CTP ctP = footerParagraph.getCTP();
CTPPr ctppr = ctP.addNewPPr();
CTString pst = ctppr.addNewPStyle();
pst.setVal("PageNumber");
// 添加页码到页脚
XWPFRun footerRun = footerParagraph.createRun();
footerRun.setText("第 ");
footerRun.getCTR().addNewFldChar().setFldCharType(STFldCharType.Enum.forString("begin"));
footerRun.getCTR().addNewInstrText().setStringValue("PAGE \\* MERGEFORMAT");
footerRun.getCTR().addNewInstrText().setSpace(SpaceAttribute.Space.Enum.forString("preserve"));
footerRun.getCTR().addNewFldChar().setFldCharType(STFldCharType.Enum.forString("end"));
footerRun.setText(" 页 共");
footerRun.getCTR().addNewFldChar().setFldCharType(STFldCharType.Enum.forString("begin"));
footerRun.getCTR().addNewInstrText().setStringValue("NUMPAGES \\* MERGEFORMAT");
footerRun.getCTR().addNewInstrText().setSpace(SpaceAttribute.Space.Enum.forString("preserve"));
footerRun.getCTR().addNewFldChar().setFldCharType(STFldCharType.Enum.forString("end"));
footerRun.setText("页 ");
// 将新的页脚添加到所有页面
headerFooterPolicy.createFooter(STHdrFtr.DEFAULT, new XWPFParagraph[]{footerParagraph});
//文件不存在,则创建父级目录
fileExists(wordFile);
FileOutputStream fileOutputStream = new FileOutputStream(wordFile);
xwpfDocument.write(fileOutputStream);
fileOutputStream.close();
template.close();