2014-02-17 34 views
3

我想用apache poi为docx文档创建一个头,但是我遇到了困难。我没有工作代码显示。我想问一些代码作为出发点。如何使用apache poi在docx文件中设置普通标题?

+0

请问你的文件已经有要更改,或者是没有任何标题一个全新的文件还没有一个头(可能是空白)? – Gagravarr

+0

这是我在poi API中生成的空白文件。我只想添加一些标题。 –

+0

你可以调用[document.getHeaderFooterPolicy()](https://poi.apache.org/apidocs/org/apache/poi/xwpf/usermodel/XWPFDocument.html#getHeaderFooterPolicy()),然后从头文件中操作那么,如果需要创建一个新的? – Gagravarr

回答

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多一点关于创建页眉和页脚。

这是不是最好的,所以它可以理想地使用某种灵魂提交补丁,使其更好的(提示提示...!),但它可以作为单元测试表明基于

+0

policy in line'XWPFHeaderFooterPolicy policy = sampleDoc.getHeaderFooterPolicy();'已经为null。基本上这是我们大多数人的问题。我们如何从文档中获取非NULL策略? –

+0

如果您的文档没有页眉页脚策略,这将是不寻常的,那么您需要先创建一个空页眉页脚。尽管如此,您仍然需要提出这个问题,因为这是OP的一个不同的问题 – Gagravarr

+0

我从头开始创建一个文档。我已经设置了所有段落并将其保存到docx。我正在重新打开该文件以向其添加页眉/页脚。不管我做什么,我的政策总是空的。 –

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(); 
} 
相关问题