如何使用Apache POI设置纯头球的docx文件? [英] How to set plain header in docx file using apache poi?

查看:162
本文介绍了如何使用Apache POI设置纯头球的docx文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Apache POI创建DOCX文档的标题,但我有困难。我没有工作code显现。我想问一些片code作为起点。

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 starting point.

推荐答案

有是一个<一个href=\"https://svn.apache.org/repos/asf/poi/trunk/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFHeader.java\"相对=nofollow> Apache的POI单元测试,涵盖你非常情况下 - 你要找的<一个href=\"https://svn.apache.org/repos/asf/poi/trunk/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFHeader.java\"相对=nofollow> TestXWPFHeader#testSetHeader()。它涵盖了开头,没有页眉或页脚设置文档,然后将其添加

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

您code将基本上是这样的:

Your code would basically be something like:

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的JavaDoc 了更多关于创建页眉和页脚位。

See the XWPFHeaderFooterPolicy JavaDocs for a bit more on creating headers and footers.

这是不是最好的,所以它可以理想地使用某种心灵提交了一个补丁,使其更好的(提示提示...!),但它可以作为单元测试显示

It isn't the nicest, so it could ideally use some kind soul submitting a patch to make it nicer (hint hint...!), but it can work as the unit tests show

这篇关于如何使用Apache POI设置纯头球的docx文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆