Bug 56511

Summary: NullPointerException by XSSFRichTextString.getFontOfFormattingRun if the first run isn't formatted
Product: POI Reporter: roger m <roger.maschewski>
Component: XSSFAssignee: POI Developers List <dev>
Status: RESOLVED FIXED    
Severity: normal    
Priority: P2    
Version: 3.10-FINAL   
Target Milestone: ---   
Hardware: PC   
OS: All   
Attachments: TestFormat.xlsx

Description roger m 2014-05-11 18:49:42 UTC
Created attachment 31604 [details]
TestFormat.xlsx

Hi,

consider an excel-file created with excel 2007 (s. attachment) that contain a cell which content is formatted in a way that the special formatting doesn't start at the first character but some positions later. This leads to the exception 

Exception in thread "main" java.lang.NullPointerException
	at org.apache.poi.xssf.usermodel.XSSFRichTextString.toCTFont(XSSFRichTextString.java:418)
	at org.apache.poi.xssf.usermodel.XSSFRichTextString.getFontOfFormattingRun(XSSFRichTextString.java:350)


Here is a straightforward program which reproduce this situation where TestFormat.xlsx is the name of the excel file attached.

try {
  FileInputStream is = new FileInputStream("c:\\TestFormat.xlsx");
  XSSFWorkbook  workbook = new XSSFWorkbook(is);
  for(XSSFSheet sheet : workbook)
  {
    int lastRow = sheet.getLastRowNum();
    for(int rowIdx = 0;rowIdx <= lastRow;rowIdx++)
    {
      XSSFRow row = sheet.getRow(rowIdx);
      int lastCell = row.getLastCellNum();

      for(int cellIdx=0;cellIdx <= lastCell; cellIdx++)
      {
        System.out.println("row "+rowIdx+" column "+cellIdx);

        XSSFCell cell = row.getCell(cellIdx);
        XSSFRichTextString richText = cell.getRichStringCellValue();
        int anzFormattingRuns = richText.numFormattingRuns();

        for(int run = 0; run < anzFormattingRuns;run++)
        {
          XSSFFont font;
          font = richText.getFontOfFormattingRun(run);
          System.out.println("run "+run+ " font "+font.getFontName());
        }
      }
    }
  }
} catch(java.io.IOException e){
      System.out.println("java.io.IOException: "+e.getMessage());
}

It outputs 
row 0 column 0
row 0 column 1
row 0 column 2
run 0 font Arial
run 1 font Arial
row 0 column 3
Exception in thread "main" java.lang.NullPointerException ...

As you can see the program crashes at the third column D. But the only difference between the content "dlgkdflgdfjkl" of the columns C and D is that in column C the first "d" is also bold and in column D not.

I think that r.getRPr() provides a null pointer that is referenced in toCTFont(). Why? Can it be corrected for POI-***-3.10-FINAL if it isn't the problem sitting before the keybord? 

Furthermore, wouldn't it be a good idea to check the result of r.getRPr() before it is passed to toCTFont within XSSFRichTextString.getFontOFormattingRun() an similar functions.

Thanks in advance
Roger
Comment 1 Dominik Stadler 2014-12-22 13:08:50 UTC
Fixed via an additional null-check added in r1647308.