How to set simple header to docx file using apache poi?

I would like to create a title for the docx document using apache poi, but I have difficulties. I have no working code to display. I would like to ask for some piece of code as a starting point.

+3
source share
2 answers

There's an Apache POI Unit test that covers your very case - you're looking for TestXWPFHeader # testSetHeader () . It covers starting with a document without a set of headers or footers, then adding them

Basically your code will look like this:

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, .

, - , , ( ...!), , -

+1

, :

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

All Articles