Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create cell with multiple styles in excel using HSSFSheet Apache POI?

I am creating a script for export document as excel.

How to have cell value like "Name: Mark DOB: 11-11-2014" by merging few cells?

like image 384
Krunal Shah Avatar asked Dec 05 '22 23:12

Krunal Shah


1 Answers

What you need to do is create a RichTextString for your cell. That's the way of applying different formatting / styles to different parts of the same cell for display in Excel

You'll want to review the POI "Working With Rich Text" example for more on how to use it, but broadly it'll be something like

    Cell cell = row.createCell(1);
    RichTextString rt = new XSSFRichTextString("The quick brown fox");

    Font font1 = wb.createFont();
    font1.setBoldWeight(Font.BOLDWEIGHT_BOLD);
    rt.applyFont(0, 10, font1);

    Font font2 = wb.createFont();
    font2.setItalic(true);
    font2.setUnderline(XSSFFont.U_DOUBLE);
    rt.applyFont(10, 19, font2);

    Font font3 = wb.createFont();
    font3.setBoldWeight(Font.BOLDWEIGHT_NORMAL);
    rt.append(" Jumped over the lazy dog", font3);

    cell.setCellValue(rt);

That should give you a cell with a mixture of bold, italic+underline and normal

like image 121
Gagravarr Avatar answered Feb 23 '23 01:02

Gagravarr