如何使用apache poi在docx文件中设置plain header?

时间:2014-02-17 14:02:02

标签: java header apache-poi docx

我想使用apache poi为docx文档创建一个标题,但我遇到了困难。我没有工作代码可以显示。我想要一些代码作为起点。

2 个答案:

答案 0 :(得分:1)

有一个Apache POI Unit test涵盖您的案例 - 您正在寻找TestXWPFHeader#testSetHeader()。它包括从没有设置页眉或页脚的文档开始,然后添加它们

您的代码基本上类似于:

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