How to replace placeholders in header of docx in java using poi 3.8

前端 未结 4 1618
醉酒成梦
醉酒成梦 2020-12-06 21:07

I\'m tying to replace tokens in the header of docx file.I have handled the token replacement in paragraphs and tables but its not picking the header data. Im using apache po

4条回答
  •  盖世英雄少女心
    2020-12-06 21:45

    I don't know if you have got the solution for this question. But, I've tried to replace tokens in document header and it worked for me.

    public XWPFDocument setHeader(XWPFDocument document, String token, String textToReplace){
        XWPFHeaderFooterPolicy policy= document.getHeaderFooterPolicy();
        XWPFHeader header = policy.getHeader(0);
        replaceInParagraphs(header.getParagraphs(), token, textToReplace);
        return document;
    }
    
    private void replaceInParagraphs(List paragraphs, String placeHolder, String replaceText){
        for (XWPFParagraph xwpfParagraph : paragraphs) {
            List runs = xwpfParagraph.getRuns();
            for (XWPFRun run : runs) {
                String runText = run.getText(run.getTextPosition());
    
                if(placeHolder !="" && !placeHolder.isEmpty()){
                    if(runText != null &&
                            Pattern.compile(placeHolder, Pattern.CASE_INSENSITIVE).matcher(runText).find()){
                        runText = replaceText;
                    }
                }
                run.setText(runText, 0);
            }
        }
    }
    

    Hope this helps. :)

提交回复
热议问题