Search code examples
javaapache-poiexcel-2007

XSSFSheet getLastRow() works but get the cells of lastrow return null


Test Test Test Test Test Test 1 2 3 4 5 6 $cell $cell $cell $cell $cell $cell

here's the code:

File file = new File("mytemplate.xlsx");
FileInputStream filein = new FileInputStream(file);

XSSFWorkbook wb = new XSSFWorkbook(filein);
filein.close();
XSSFSheet sheet = wb.getSheetAt(0);
int lastrow = sheet.getLastRowNum();
int phyrow = sheet.getPhysicalNumberOfRows();

XSSFRow modlrow = sheet.createRow(lastrow);----still work, modlrow = 2
System.out.println(sheet.getRow(0).getCell(2));---still work
System.out.println(sheet.getRow(1).getCell(2));  ---still work
System.out.println(sheet.getRow(lastrow).getCell(2)+"=========");don't work

Solution

  • Your problem is these two lines:

    XSSFRow modlrow = sheet.createRow(lastrow);----still work, modlrow = 2
    System.out.println(sheet.getRow(lastrow).getCell(2)+"=========");don't work
    

    The first one creates a brand new, empty row. The second tries to read from a specific cell in a row with no creation

    You either need to explicitly create that cell, eg:

    XSSFRow modlrow = sheet.createRow(lastrow);
    modlrow.createCell(2);
    System.out.println(sheet.getRow(lastrow).getCell(2)+"=========");
    

    Or do your fetch with a Missing Cell Policy to have the non-existant cell created for you on demand, eg:

    XSSFRow modlrow = sheet.createRow(lastrow);
    modlrow.createCell(2);
    System.out.println(sheet.getRow(lastrow).getCell(2, MissingCellPolicy.CREATE_NULL_AS_BLANK)+"=========");