How to Highlight a text for a Pargraph in MS word using POI

爱⌒轻易说出口 提交于 2020-01-01 19:22:30

问题


I am developing a compare tool for the word document, whenever there is difference in both the document i need to highlight the substring in the paragraph.When i try to highlight using run, its highlighting whole paragraph instead of the sub string.

Can you please guide us, how can i achieve this for a substring.


回答1:


I had the same problem. Here I post a sample method where you highlight a substring contained in a run.

private int highlightSubsentence(String sentence, XWPFParagraph p, int i) {
    //get the current run Style - here I might need to save the current style
    XWPFRun currentRun = p.getRuns().get(i);
    String currentRunText = currentRun.text();
    int sentenceLength = sentence.length();
    int sentenceBeginIndex = currentRunText.indexOf(sentence);
    int addedRuns = 0;
    p.removeRun(i);
    //Create, if necessary, a run before the highlight part
    if (sentenceBeginIndex > 0) {
        XWPFRun before = p.insertNewRun(i);
        before.setText(currentRunText.substring(0, sentenceBeginIndex));
        //here I might need to re-introduce the style of the deleted run
        addedRuns++;
    }

    // highlight the interesting part
    XWPFRun sentenceRun = p.insertNewRun(i + addedRuns);
    sentenceRun.setText(currentRunText.substring(sentenceBeginIndex, sentenceBeginIndex + sentenceLength));
    currentStyle.copyStyle(sentenceRun);
    CTShd cTShd = sentenceRun.getCTR().addNewRPr().addNewShd();
    cTShd.setFill("00FFFF");

    //Create, if necessary, a run after the highlight part
    if (sentenceBeginIndex + sentenceLength != currentRunText.length()) {
        XWPFRun after = p.insertNewRun(i + addedRuns + 1);
        after.setText(currentRunText.substring(sentenceBeginIndex + sentenceLength));
        //here I might need to re-introduce the style of the deleted run
        addedRuns++;
    }
    return addedRuns;
}

You might need to save the formatting style of the run you delete in order to have the new runs with the old formatting.

Also, if the string you need to highlight is spread over more than one run, you will need to highlight all of them, but the core method is the one I posted.



来源:https://stackoverflow.com/questions/44242516/how-to-highlight-a-text-for-a-pargraph-in-ms-word-using-poi

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!