blond1995
blond1995

Reputation: 27

How to determine the color of the one part of the text in cell by Apache POI

I have Excel table. In the cell we can have text (for example text1;text2) and part 1 (text1) of this text will have black color, but another one (text2) have, for example, red color. For read Excel file I use Apache POI.

Could you please ask how to determine the color (which in our case is red) of THAT second part of the text.

For determination of the whole text in the cell I use now this code:

      HSSFCellStyle cellStyle = (HSSFCellStyle) currentCell.getCellStyle();
        short cellColor = cellStyle.getFont(currentCell.getSheet().getWorkbook()).getColor();

I don't know if it determinate it correct

Upvotes: 1

Views: 684

Answers (1)

Gagravarr
Gagravarr

Reputation: 48326

You need to fetch the cell's contents as a RichTextString and then get the formatting information from that

For HSSF, your code would want to be something like:

HSSFRichTextString richTextString = hssfCell.getRichStringCellValue();
for (int i=0; i<richTextString.0,r.numFormattingRuns(); i++) {
    if (richTextString.getFontAtIndex(i) == HSSFRichTextString.NO_FONT) {
        // Default cell formatting rules apply to this bit
    } else {
        HSSFFont font = workbook.getFontAt(richTextString.getFontAtIndex(i));
        // This bit of the string has the above font
    }
}

You can use methods like getIndexOfFormattingRun() to work out where in the string the font changes

Upvotes: 2

Related Questions