【问题标题】:How to add Header and Footer in a word document using POI api?如何使用 POI api 在 word 文档中添加页眉和页脚?
【发布时间】:2015-04-13 22:31:46
【问题描述】:

我尝试使用以下代码在文档中添加页脚,但效果不佳。

  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-schemas-3.10-FINAL-20140208.jar
  4. poi-scratchpad-3.10-FINAL-20140208

【问题讨论】:

  • “无法正常工作”是什么意思?部分工作?给出错误?显示错误?还有就是没有显示保存文件的代码,能这么简单吗?
  • 您能帮忙完成代码吗?请告诉我如何将其保存到文件中?
  • 要保存文件,无论您使用什么格式,都一样 - 只需调用 write(OutputStream)
  • 感谢 Gagravarr 的帮助。它奏效了。

标签: java apache-poi


【解决方案1】:

提升对答案的评论...

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

您的代码不会在您进行更改后将文件写出!

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

FileOutputStream out = new FileOutputStream("WithHeader.docx");
document.write(out);
out.close();

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 这个答案应该对sn-p有一些解释。
    猜你喜欢
    • 1970-01-01
    • 2013-03-09
    • 2023-03-29
    • 2014-12-02
    • 2021-07-21
    • 1970-01-01
    • 2012-07-25
    • 2014-05-21
    • 2017-03-29
    相关资源
    最近更新 更多