如何使用 apache poi 在 docx 文件中设置普通标题? [英] How to set plain header in docx file using apache poi?
问题描述
我想使用 apache poi 为 docx 文档创建标题,但我遇到了困难.我没有可显示的工作代码.我想要求一些代码作为起点.
I would like to create a header for docx document using apache poi but I have difficulties. I have no working code to show. I would like to ask for some piece of code as starting point.
推荐答案
有一个 Apache POI 单元测试 涵盖您的情况 - 您正在寻找 TestXWPFHeader#testSetHeader().它涵盖从没有设置页眉或页脚的文档开始,然后添加它们
There's an Apache POI Unit test that covers your very case - you're looking for TestXWPFHeader#testSetHeader(). It covers starting with a document with no headers or footers set, then adding them
您的代码基本上类似于:
Your code would basically be something like:
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
}
请参阅 XWPFHeaderFooterPolicy JavaDocs更多关于创建页眉和页脚的内容.
See the XWPFHeaderFooterPolicy JavaDocs for a bit more on creating headers and footers.
它不是最好的,因此理想情况下它可以使用某种灵魂提交补丁使其更好(提示提示......!),但它可以像单元测试显示的那样工作
It isn't the nicest, so it could ideally use some kind soul submitting a patch to make it nicer (hint hint...!), but it can work as the unit tests show
这篇关于如何使用 apache poi 在 docx 文件中设置普通标题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!