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

前端 未结 2 1959
悲哀的现实
悲哀的现实 2021-01-14 08:38

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 sta

2条回答
  •  执笔经年
    2021-01-14 09:42

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

提交回复
热议问题