Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apache POI: Partial Cell fonts

If I crack open MS Excel (I assume), or LibreOffice Calc (tested), I can type stuff into a cell, and change the font of parts of the text in a cell, such as doing, in one cell, :

This text is bold and this text is italicized

Again, let me reiterate, that this string could exist in the shown format in one cell.

Can this level of customization be achieved with Apache POI? Searching only seems to show how to apply a font to an entire cell.

Thanks

===UPDATE===

As suggested below, I ended up going with the HSSFRichTextString (as I'm working with HSSF). However, after applying fonts (I tried bold and underline), my text would remain unchanged. This is what I attempted. To put things in context, I am working on something sports-related, in which it is common to display a match up in the form "awayteam"@"hometeam", and depending on certain external conditions, I would like to make one or the other bold. My code looks something like this:

    String away = "foo";
    String home = "bar";
    String bolden = "foo"
    HSSFRichTextString val = new HSSFRichTextString(away+"@"+home);

    if(bolden.equals(home)) {
        val.applyFont(val.getString().indexOf("@") + 1, val.length(), Font.U_SINGLE);
    } else if(bolden.equals(away)) {
        val.applyFont(0, val.getString().indexOf("@"), Font.U_SINGLE);
    }
    gameHeaderRow.createCell(g + 1).setCellValue(val);

As you can see, this is a snippet of code from a more complicated function than is displayed, but the brunt of this is actual code. As you can see, I'm doing val.applyFont to part of a string, and then setting a cell value with the string. So I'm not entirely sure what I did wrong there. Any advice is appreciated.

Thanks

KFJ

like image 372
Cody S Avatar asked Mar 07 '12 06:03

Cody S


2 Answers

POI does support it, the class you're looking for is RichTextString. If your cell is a text one, you can get a RichTextString for it, then apply fonts to different parts of it to make different parts of the text look different.

like image 114
Gagravarr Avatar answered Nov 08 '22 09:11

Gagravarr


You would be drained if working with SXSSFWorkbook, as it does not support such formatting. Check it here. http://apache-poi.1045710.n5.nabble.com/RichTextString-isn-t-working-for-SXSSFWorkbook-td5711695.html

like image 41
Rohit Verma Avatar answered Nov 08 '22 10:11

Rohit Verma