Apache POI 如何添加页码 [英] Apache POI how to add a page number

查看:196
本文介绍了Apache POI 如何添加页码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

刚开始使用 POI 3.10 创建 Word 文档(XWPF).大多数事情都是直截了当的,但我不明白如何添加页码.我添加了页脚,但是页脚中的文字在每一页上都是一样的

Just started to use POI 3.10 to create a Word document (XWPF). Most of the things are straight forward, but I don't understand how to add page numbers. I added the footer, but the text in the footer is the same on every page

推荐答案

我在 LibreOffice 右侧的页脚中创建了一个页码并调查了 XML 文件(在使用的 POI 中不支持 MS Word-Std-Objects那里有页码).

I created a page number in the footer on the right in LibreOffice and investigated the XML file (MS Word-Std-Objects are not supported in POI which is used there for page numbers).

这将能够创建更复杂的页脚...

This will enable to create more complex footers...

要将数字设置为其他位置,请为 ctjc 设置另一个值而不是 STJc.RIGHT...

to set the number to other positions set another value for ctjc instead of STJc.RIGHT...

结果如下:

// create footer
XWPFHeaderFooterPolicy policy = doc.getHeaderFooterPolicy();
CTP ctpFooter = CTP.Factory.newInstance();

XWPFParagraph[] parsFooter;

// add style (s.th.)
CTPPr ctppr = ctpFooter.addNewPPr();
CTString pst = ctppr.addNewPStyle();
pst.setVal("style21");
CTJc ctjc = ctppr.addNewJc();
ctjc.setVal(STJc.RIGHT);
ctppr.addNewRPr();

// Add in word "Page "   
CTR ctr = ctpFooter.addNewR();
CTText t = ctr.addNewT();
t.setStringValue("Page ");
t.setSpace(Space.PRESERVE);

// add everything from the footerXXX.xml you need
ctr = ctpFooter.addNewR();
ctr.addNewRPr();
CTFldChar fch = ctr.addNewFldChar();
fch.setFldCharType(STFldCharType.BEGIN);

ctr = ctpFooter.addNewR();
ctr.addNewInstrText().setStringValue(" PAGE ");

ctpFooter.addNewR().addNewFldChar().setFldCharType(STFldCharType.SEPARATE);

ctpFooter.addNewR().addNewT().setStringValue("1");

ctpFooter.addNewR().addNewFldChar().setFldCharType(STFldCharType.END);

XWPFParagraph footerParagraph = new XWPFParagraph(ctpFooter, doc);

parsFooter = new XWPFParagraph[1];

parsFooter[0] = footerParagraph;

policy.createFooter(XWPFHeaderFooterPolicy.DEFAULT, parsFooter);

这篇关于Apache POI 如何添加页码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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