我想用 XWPF jars (apache poi) 在 docx 文档(新文档而不是现有文档)上创建一个页眉和页脚。
当我使用XWPFHeaderFooterPolicy policy = document.getHeaderFooterPolicy();
策略为空时,我会知道如何在新文档中创建它。
CustomXWPFDocument document = new CustomXWPFDocument();
XWPFHeaderFooterPolicy policy = document.getHeaderFooterPolicy();
XWPFHeader head = policy.createHeader(policy.DEFAULT);
head.getListParagraph().get(0).createRun().setText("Hello Header World!");
CTP ctP1 = CTP.Factory.newInstance();
CTR ctR1 = ctP1.addNewR();
CTText t = ctR1.addNewT();
t.setStringValue("Paragraph in header");
XWPFParagraph p1 = new XWPFParagraph(ctP1, document);
XWPFParagraph[] pars = new XWPFParagraph[1];
pars[0] = p1;
policy.createHeader(policy.FIRST, pars);
必须
使用以下代码将节属性添加到XWPFDocument doc
(如果尚不存在)
CTBody body = doc.getDocument().getBody();
CTSectPr sectPr = body.isSetSectPr()? body.getSectPr() : body.addNewSectPr();
public static void setFooter(XWPFDocument document, String footerText) {
CTP ctpFooter = CTP.Factory.newInstance();
ctpFooter.addNewR().addNewT();
XWPFParagraph footerParagraph = new XWPFParagraph(ctpFooter, document);
XWPFRun footerRun = createFormattedRun(footerParagraph);
footerRun.setFontSize(6);
footerRun.setText(footerText);
XWPFParagraph[] parsFooter = new XWPFParagraph[1];
parsFooter[0] = footerParagraph;
CTSectPr sectPr = document.getDocument().getBody().addNewSectPr();
XWPFHeaderFooterPolicy policy = new XWPFHeaderFooterPolicy(document, sectPr);
policy.createFooter(XWPFHeaderFooterPolicy.DEFAULT, parsFooter);
}
我遇到了同样的问题,但没有找到任何解决方案。在这种情况下,我创建了带有页眉和页脚的模板docx文件,然后更改它们。这种做法我在 Apache 邮件档案中找到了。