How to set plain header in docx file using apache poi?

北城余情 提交于 2019-12-01 07:07:54

问题


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();
}


来源:https://stackoverflow.com/questions/21831067/how-to-set-plain-header-in-docx-file-using-apache-poi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!