如何使用POI api在单词文档中添加页眉和页脚?

时间:2014-10-17 05:50:51

标签: java apache-poi

我尝试使用代码在我的文档中添加页脚,但它运行不正常。

  CTP ctp = CTP.Factory.newInstance();
    CTR ctr = ctp.addNewR();
    CTRPr rpr = ctr.addNewRPr();
    CTText textt = ctr.addNewT();
    textt.setStringValue( " Page 1" );
    XWPFParagraph codePara = new XWPFParagraph( ctp, document );
    XWPFParagraph[] newparagraphs = new XWPFParagraph[1];
    newparagraphs[0] = codePara;
    CTSectPr sectPr1 = document.getDocument().getBody().addNewSectPr();
    XWPFHeaderFooterPolicy headerFooterPolicy = new  XWPFHeaderFooterPolicy( document,sectPr1 );

headerFooterPolicy.createFooter( STHdrFtr.DEFAULT, newparagraphs );

我正在使用以下jar来生成我的文档。请帮忙......

  1. POI-3.10-FINAL-20140208.jar
  2. POI-OOXML-3.10-FINAL-20140208.jar
  3. POI-OOXML-架构 - 3.10-FINAL-20140208.jar
  4. POI暂存器-3.10-FINAL-20140208

2 个答案:

答案 0 :(得分:0)

宣传回答评论......

问题不在于页眉/页脚代码。你问题中的代码看起来很适合做你想做的事情。如果您确实想要做更多的事情,那么我想到的最好的参考是unit tests for headers and footers in Apache POI,它涵盖了更多的用例

您的代码不做的是在您完成更改后写出文件!

您只需在代码末尾添加对write(OutputStream)的调用,即可完成。像

这样的东西
FileOutputStream out = new FileOutputStream("WithHeader.docx");
document.write(out);
out.close();

答案 1 :(得分:-1)

Adding footer to ms word using POI api

CTP ctp = CTP.Factory.newInstance();
        CTR ctr = ctp.addNewR();
        CTRPr rpr = ctr.addNewRPr();
        CTText textt = ctr.addNewT();
        textt.setStringValue( " Page 1" );
        XWPFParagraph codePara = new XWPFParagraph( ctp, document );
        XWPFParagraph[] newparagraphs = new XWPFParagraph[1];
        newparagraphs[0] = codePara;
        CTSectPr sectPr = document.getDocument().getBody().addNewSectPr();
        XWPFHeaderFooterPolicy headerFooterPolicy = new  XWPFHeaderFooterPolicy( document, sectPr );
        headerFooterPolicy.createFooter( STHdrFtr.DEFAULT, newparagraphs );