Java 使用 POI 为 word 添加页眉 获取页眉

在百度上和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());//页眉
        }
    }
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值