我想使用 apache poi 为 docx 文档创建标头,但我遇到了困难。我没有可以显示的工作代码。我想请求一些代码作为起点。
有一个Apache POI 单元测试这涵盖了您的具体情况 - 您正在寻找TestXWPFHeader#testSetHeader()。它涵盖从没有设置页眉或页脚的文档开始,然后添加它们
你的代码基本上是这样的:
XWPFHeaderFooterPolicy policy = sampleDoc.getHeaderFooterPolicy();
if (policy.getDefaultHeader() == null && policy.getFirstPageHeader() == null
&& policy.getDefaultFooter() == null) {
// Need to create some new headers
// The easy way, gives a single empty paragraph
XWPFHeader headerD = policy.createHeader(policy.DEFAULT);
headerD.getParagraphs(0).createRun().setText("Hello Header World!");
// Or the full control way
CTP ctP1 = CTP.Factory.newInstance();
CTR ctR1 = ctP1.addNewR();
CTText t = ctR1.addNewT();
t.setStringValue("Paragraph in header");
XWPFParagraph p1 = new XWPFParagraph(ctP1, sampleDoc);
XWPFParagraph[] pars = new XWPFParagraph[1];
pars[0] = p1;
policy.createHeader(policy.FIRST, pars);
} else {
// Already has a header, change it
}
See the XWPFHeaderFooterPolicy JavaDocs有关创建页眉和页脚的更多信息。
它不是最好的,所以理想情况下它可以使用某种灵魂提交补丁来使其更好(提示提示......!),但它可以像单元测试所示那样工作
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)