我的.docx文档中有一个文本标题,与左侧对齐。 我想在页眉的右侧添加页码作为“页面1”,“页面2”等。我正在使用Apache POI,是否有任何可能的方法来做同样的事情。我正在使用下面一段代码添加左对齐标题 -
XWPFDocument document = new XWPFDocument();
CTSectPr sectPr = document.getDocument().getBody().addNewSectPr();
XWPFHeaderFooterPolicy policy = new XWPFHeaderFooterPolicy(document, sectPr);
//write header content
CTP ctpHeader = CTP.Factory.newInstance();
CTR ctrHeader = ctpHeader.addNewR();
CTText ctHeader = ctrHeader.addNewT();
String headerText = "This is a header";
ctHeader.setStringValue(headerText);
XWPFParagraph headerParagraph = new XWPFParagraph(ctpHeader, document);
XWPFParagraph[] parsHeader = new XWPFParagraph[1];
parsHeader[0] = headerParagraph;
policy.createHeader(XWPFHeaderFooterPolicy.DEFAULT, parsHeader);`
请帮助我解决这个问题。
答案 0 :(得分:0)
问题已解决。我现在能够在标题中添加正确对齐的页码。
我使用以下链接作为参考 - Apache POI how to add a page number
以下代码现在可以正常使用 -
XWPFDocument document = new XWPFDocument();
CTSectPr sectPr = document.getDocument().getBody().addNewSectPr();
XWPFHeaderFooterPolicy policy = new XWPFHeaderFooterPolicy(document, sectPr);
//write header content
CTP ctpHeader = CTP.Factory.newInstance();
CTR ctrHeader = ctpHeader.addNewR();
CTText ctHeader = ctrHeader.addNewT();
String headerText = "FISHER SCIENTIFIC COMPANY L.L.C. DISTRIBUTION AGREEMENT";
ctHeader.setStringValue(headerText);
//write page number header
CTP ctpHeaderPage = CTP.Factory.newInstance();
CTPPr ctppr = ctpHeaderPage.addNewPPr();
CTString pst = ctppr.addNewPStyle();
pst.setVal("style21");
CTJc ctjc = ctppr.addNewJc();
ctjc.setVal(STJc.RIGHT);
ctppr.addNewRPr();
CTR ctr = ctpHeaderPage.addNewR();
ctr.addNewRPr();
CTFldChar fch = ctr.addNewFldChar();
fch.setFldCharType(STFldCharType.BEGIN);
ctr = ctpHeaderPage.addNewR();
ctr.addNewInstrText().setStringValue(" PAGE ");
ctpHeaderPage.addNewR().addNewFldChar().setFldCharType(STFldCharType.SEPARATE);
ctpHeaderPage.addNewR().addNewT().setStringValue("1");
ctpHeaderPage.addNewR().addNewFldChar().setFldCharType(STFldCharType.END);
XWPFParagraph headerParagraph = new XWPFParagraph(ctpHeader, document);
XWPFParagraph headerParagraphPage = new XWPFParagraph(ctpHeader, document);
XWPFParagraph[] parsHeader = new XWPFParagraph[2];
parsHeader[0] = headerParagraph;
parsHeader[1] = headerParagraphPage;
policy.createHeader(XWPFHeaderFooterPolicy.DEFAULT, parsHeader);