在百度上和goole都没找到我想要的东西,看了他的接口注释他的官方文档之后才得到了这个解决方案
// POI方案为word添加页眉
public static void main(String[] args) throws IOException {
File is = new File("C:\\upload\\20190510_141809278_Test.docx");//文件路径
FileInputStream fis = new FileInputStream(is);
XWPFDocument docx = new XWPFDocument(fis);//文档对象
CTP ctp = CTP.Factory.newInstance();
XWPFParagraph paragraph = new XWPFParagraph(ctp, docx);//段落对象
ctp.addNewR().addNewT().setStringValue("华丽的测试页眉2019051488888888");//设置页眉参数
ctp.addNewR().addNewT().setSpace(SpaceAttribute.Space.PRESERVE);
CTSectPr sectPr = docx.getDocument().getBody().isSetSectPr() ? docx.getDocument().getBody().getSectPr() : docx.getDocument().getBody().addNewSectPr();
XWPFHeaderFooterPolicy policy = new XWPFHeaderFooterPolicy(docx, sectPr);
XWPFHeader header = policy.createHeader(STHdrFtr.DEFAULT, new XWPFParagraph[] { paragraph });
header.setXWPFDocument(docx);
OutputStream os = new FileOutputStream("d:\\Test.docx");
docx.write(os);//输出到本地
}
再贴一个获取word页眉的方案
// POI 方案获取word页眉
public static void main(String[] args) throws IOException {
File is = new File("d:\\Test.docx");//文件路径
FileInputStream fis = new FileInputStream(is);
XWPFDocument docx = new XWPFDocument(fis);
List<XWPFHeader> headerList = docx.getHeaderList();
for (XWPFHeader xwpfHeader: headerList){
System.out.println(xwpfHeader.getText());//页眉
}
}