最近遇到一个问题,就是导出word设置页脚的页码且奇偶数不同,效果如下。
贴一下代码,记录一下。
/**
* 创建页脚
*
* @param document doc对象
* @throws IOException
* @throws NoSuchFieldException
* @throws IllegalAccessException
*/
public static void createFooter(XWPFDocument document) throws IOException, NoSuchFieldException, IllegalAccessException {
Field _settings = XWPFDocument.class.getDeclaredField("settings");
_settings.setAccessible(true);
XWPFSettings xwpfsettings = (XWPFSettings) _settings.get(document);
Field _ctSettings = XWPFSettings.class.getDeclaredField("ctSettings");
_ctSettings.setAccessible(true);
org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSettings ctSettings =
(org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSettings) _ctSettings.get(xwpfsettings);
ctSettings.addNewEvenAndOddHeaders();
XWPFFooter footer = document.createFooter(HeaderFooterType.DEFAULT);
//奇数
XWPFParagraph paragraph = footer.createParagraph();
paragraph.setAlignment(ParagraphAlignment.RIGHT);
XWPFRun run;
run = paragraph.createRun();
run.setText("— ");
CTFldChar fldChar = run.getCTR().addNewFldChar();
fldChar.setFldCharType(STFldCharType.Enum.forString("begin"));
setXWPFRunStyle(run, "宋体", 14);
CTText ctText = run.getCTR().addNewInstrText();
ctText.setStringValue("PAGE \\* MERGEFORMAT");
ctText.setSpace(SpaceAttribute.Space.Enum.forString("preserve"));
setXWPFRunStyle(run, "宋体", 14);
fldChar = run.getCTR().addNewFldChar();
fldChar.setFldCharType(STFldCharType.Enum.forString("end"));
run.setText(" —");
//偶数
XWPFParagraph paragraph1 = document.createFooter(HeaderFooterType.EVEN).createParagraph();
paragraph1.setAlignment(ParagraphAlignment.LEFT);
XWPFRun run1;
run1 = paragraph1.createRun();
run1.setText("— ");
CTFldChar fldChar1 = run1.getCTR().addNewFldChar();
fldChar1.setFldCharType(STFldCharType.Enum.forString("begin"));
setXWPFRunStyle(run1, "宋体", 14);
CTText ctText1 = run1.getCTR().addNewInstrText();
ctText1.setStringValue("PAGE \\* MERGEFORMAT");
ctText1.setSpace(SpaceAttribute.Space.Enum.forString("preserve"));
setXWPFRunStyle(run1, "宋体", 14);
fldChar1 = run1.getCTR().addNewFldChar();
fldChar1.setFldCharType(STFldCharType.Enum.forString("end"));
run1.setText(" —");
}
/**
* 设置页脚的字体样式
*
* @param r1 段落元素
* @param font 字体
* @param fontSize 字体大小
*/
private static void setXWPFRunStyle(XWPFRun r1, String font, int fontSize) {
r1.setFontSize(fontSize);
CTRPr rpr = r1.getCTR().isSetRPr() ? r1.getCTR().getRPr() : r1.getCTR().addNewRPr();
CTFonts fonts = rpr.isSetRFonts() ? rpr.getRFonts() : rpr.addNewRFonts();
fonts.setAscii(font);
fonts.setEastAsia(font);
fonts.setHAnsi(font);
}
评论 (0)