Search code examples
javaexcelapache-poixssf

Why does not XSSFRichTextString.applyFont() work as it is written in java doc?


I am trying to apply bold font on parts of a string and place it in a cell.

XSSFFont font = workbook.createFont();
font.setBold(true);
XSSFCellStyle style = workbook.createCellStyle();
style.setFont(font);
XSSFCell c = nextRow.createCell(4);
c.setCellStyle(style);
XSSFRichTextString string = new XSSFRichTextString(report.getSurroundText());
string.applyFont( startIndex, getEndOfWord(startIndex, report.getFoundWord()), font); 
c.setCellValue(string);

This code, as part of my code that produces an .xlsx file and it does produce a not corrupt file, but the text that should be bold is not correct. Instead it highlights from the start of the text to the index I set as end index in the applyFont() method. Basicly for some reason startIndex is ignored.

During debug, both startIndex and the return value of getEndOfWord() is correct.

EDIT:

try(FileOutputStream fileOut = new FileOutputStream(new File(directory.getAbsoluteFile() + File.separator + 
            FilenameUtils.getBaseName(csvFile.getAbsolutePath()) + ".xlsx"));) {
        try (XSSFWorkbook workbook = new XSSFWorkbook()) {
            XSSFSheet sheet = workbook.createSheet("Highlights");
            XSSFRow headerRow = sheet.createRow(0);
            headerRow.createCell(0).setCellValue(firstLine);

            XSSFRow titleRow = sheet.createRow(1);
            titleRow.createCell(0).setCellValue(SCANID);
            titleRow.createCell(1).setCellValue(DOCID);
            titleRow.createCell(2).setCellValue(FOUNDWORD);
            titleRow.createCell(3).setCellValue(OFFSET);
            titleRow.createCell(4).setCellValue(SURROUNDTEXT);

            XSSFFont font = workbook.createFont();
            font.setBold(true);
            XSSFFont deFont = workbook.createFont();
            font.setBold(false);

            int row = 2;
            for (MuiDetailReport report : lst) {
                XSSFRow nextRow = sheet.createRow(row);
                nextRow.createCell(0).setCellValue(report.getScanId());
                nextRow.createCell(1).setCellValue(report.getDocId());
                nextRow.createCell(2).setCellValue(report.getFoundWord());
                if (report.getOffset() != 0) nextRow.createCell(3).setCellValue(report.getOffset());
                else nextRow.createCell(3).setCellValue("");
                if (!report.getFoundWord().isBlank() && !report.getSurroundText().isBlank()) {
                    int startIndex = getStartOfWord(report.getFoundWord(), report.getSurroundText());
                    if (startIndex == -1) nextRow.createCell(4).setCellValue("");
                    else {
                        XSSFCell c = nextRow.createCell(4);
                        XSSFRichTextString string = new XSSFRichTextString(report.getSurroundText());
                        string.applyFont(startIndex, getEndOfWord(startIndex, report.getFoundWord()), font);
                        c.setCellValue(string);
                    }
                } else nextRow.createCell(4).setCellValue("");
                row++;
            }
            workbook.write(fileOut);
        }
        fileOut.flush();
    }

This is my method for creating my .xlsx file. Method parameter: String firstLine, List<MuiDetailReport> lst, File csvFile. Variable with all uppercase characters are static final String

My result is "HellomynameisThad" instead of "HellomynameisThad"


Solution

  • Let's have a really Minimal, Reproducible Example.

    The folowing should result in having the text

    HellomynameisThad

    in Cell A1.

    import java.io.FileOutputStream;
    import org.apache.poi.ss.usermodel.*;
    import org.apache.poi.xssf.usermodel.XSSFWorkbook;
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    
    class CreateExcelBoldWord {
    
     public static void main(String[] args) throws Exception {
    
      Workbook workbook = new XSSFWorkbook(); 
      //Workbook workbook = new HSSFWorkbook();
    
      String fileName = (workbook instanceof XSSFWorkbook)?"Excel.xlsx":"Excel.xls";
    
      CreationHelper creationHelper = workbook.getCreationHelper();
    
      Font font = workbook.createFont(); // default font
      Font fontBold = workbook.createFont();
      fontBold.setBold(true);
    
      String text = "HellomynameisThad";
      String word = "name";
    
      RichTextString richTextString = creationHelper.createRichTextString(text);
      int startIndex = text.indexOf(word);
      int endIndex = startIndex + word.length();
      richTextString.applyFont(startIndex, endIndex, fontBold);
    
      Sheet sheet = workbook.createSheet();
      sheet.createRow(0).createCell(0).setCellValue(richTextString);
    
      FileOutputStream out = new FileOutputStream(fileName);
      workbook.write(out);
      out.close();
      workbook.close();
     }
    }
    

    No?