使用apache poi在doc文件中设置颜色文本

时间:2013-04-08 09:28:00

标签: java ms-word apache-poi hwpf

我使用此代码段在MS Word文件中设置彩色文本

CharacterRun r = paragraph.getCharacterRun(2).insertBefore("x");
r = r.insertBefore("y");
r.setColor(6);
r.insertBefore("z);

我想将颜色设置为仅“y”字符,但我得到的结果是“x”,“y”,“z”都设置为红色。我错了吗?如何将颜色设置为仅“y”字符 - 第二个CharacterRun。

提前致谢

1 个答案:

答案 0 :(得分:0)

我认为迟到总比不到好: 您可能正在为整个包含运行设置颜色。 您需要做的是:

  • 从当前运行中删除溢出的文本
  • 在相邻的运行中添加溢出文本
  • 为当前运行着色

这是一个例子

private void highlightSubsentence(String currentRunText, String sentence, CharacterRun currentRun, int runIndex, Paragraph p, HighlighterColor color) {
        int sentenceBeginIndex = currentRunText.indexOf(sentence, 0);
        int sentenceLength = sentence.length();
        String leftSentence = currentRunText.substring(0, sentenceBeginIndex);
        String rightSentence = currentRunText.substring(sentenceBeginIndex + sentenceLength);
        boolean leftOverflow = sentenceBeginIndex > 0;
        boolean rightOverflow = sentenceBeginIndex + sentenceLength < currentRunText.length();
        boolean isInTable = p.isInTable();
        if (rightOverflow && !isInTable && runIndex + 1 < p.numCharacterRuns()) {
            currentRun.replaceText(sentence + rightSentence, sentence);
            p.getCharacterRun(runIndex + 1).insertBefore(rightSentence);
        }
        if (leftOverflow && !isInTable && runIndex > 0) {
            currentRun.replaceText(leftSentence + sentence, sentence);
            p.getCharacterRun(runIndex - 1).insertAfter(leftSentence);
        }
        currentRun.setColor(6);
    }