0

In below code, I intend to have "Jack Reacher" in bold style and the rest of the string as normal font. I am not able to see the newline appended in report after "Jack Reacher". Newline gets applied if I comment and ignore bold descEntryRichStr.applyFont(0, name.length() , boldedFont);

I have added cs.setWrapText(true); also but it still doesnt work

XSSFWorkbook workbook = new XSSFWorkbook();
    XSSFSheet sheet = workbook.createSheet("Test First");

    XSSFFont boldedFont = workbook.createFont();
    boldedFont.setBoldweight(Font.BOLDWEIGHT_BOLD);

    String newLine  = "\n";
    String name = "Jack Reacher";
    String fileNo = "Professsion : Doctor";
    String other = "Address : New-york" ;

    String finalString = name +newLine + fileNo + newLine + other;

    Row row = sheet.createRow(0); 
    XSSFCell cell = (XSSFCell) row.createCell(0);

    CreationHelper creationHelper = workbook.getCreationHelper();

    XSSFRichTextString descEntryRichStr = (XSSFRichTextString) creationHelper.createRichTextString(finalString);
    descEntryRichStr.applyFont(0, name.length() , boldedFont);
    cell.setCellValue(descEntryRichStr);
    XSSFCellStyle cs = cell.getCellStyle();
    cs.setWrapText(true);
    cell.setCellStyle(cs);

    System.out.println(cell.getStringCellValue());

    try (FileOutputStream outputStream = new FileOutputStream("/shared/sample/report-"+new Date().getTime() +".xlsx")) {
        workbook.write(outputStream);
    }

Here is the snippet of report

  • Already applied the solution as suggested. But it still doesnt work. Here in my case , the issue is due to applying separate fonts in the cell string – riyaj sande Jul 31 '18 at 14:23
  • Voted to reopen. The linked answer states that `setWrapText(true)` must be used. But this is exactly what @riyaj sande already does. The problem is that he does this in the default cell style. Either he should creating a new cell style or, better, he should use `org.apache.poi.ss.util.CellUtil` to set cell style property: `org.apache.poi.ss.util.CellUtil.setCellStyleProperty(cell, org.apache.poi.ss.util.CellUtil.WRAP_TEXT, true);` – Axel Richter Jul 31 '18 at 15:43
  • @Gagravarr: How is this a duplicate of the answer you linked? The linked answer states that setWrapText(true) must be used. But this is exactly what riyaj sande already does. – Axel Richter Jul 31 '18 at 15:45
  • Thank you @ Axel Richter for the solution. I was using old 3.6 dependency version. The code works in case dependency is 3.9 or more, with using either setWrapText(true) OR CellUtil.setCellStyleProperty() – riyaj sande Aug 01 '18 at 07:38

0 Answers0