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.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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
}
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
回答2:
Based on the previous answer, just copy and paste:
public void test1() throws IOException{
XWPFDocument sampleDoc = new XWPFDocument();
XWPFHeaderFooterPolicy policy = sampleDoc.getHeaderFooterPolicy();
//in an empty document always will be null
if(policy==null){
CTSectPr sectPr = sampleDoc.getDocument().getBody().addNewSectPr();
policy = new XWPFHeaderFooterPolicy( sampleDoc, sectPr );
}
if (policy.getDefaultHeader() == null && policy.getFirstPageHeader() == null
&& policy.getDefaultFooter() == null) {
XWPFHeader headerD = policy.createHeader(policy.DEFAULT);
headerD.getParagraphs().get(0).createRun().setText("Hello Header World!");
}
FileOutputStream out = new FileOutputStream(System.currentTimeMillis()+"_test1_header.docx");
sampleDoc.write(out);
out.close();
sampleDoc.close();
}