Index: src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFEvaluationSheet.java =================================================================== --- src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFEvaluationSheet.java (revision 1848483) +++ src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFEvaluationSheet.java (working copy) @@ -34,11 +34,9 @@ private final XSSFSheet _xs; private Map _cellCache; - private int _lastDefinedRow = -1; public XSSFEvaluationSheet(XSSFSheet sheet) { _xs = sheet; - _lastDefinedRow = _xs.getLastRowNum(); } public XSSFSheet getXSSFSheet() { @@ -51,7 +49,7 @@ */ @Override public int getLastRowNum() { - return _lastDefinedRow; + return _xs.getLastRowNum(); } /* (non-JavaDoc), inherit JavaDoc from EvaluationWorkbook @@ -60,7 +58,6 @@ @Override public void clearAllCachedResultValues() { _cellCache = null; - _lastDefinedRow = _xs.getLastRowNum(); } @Override @@ -67,7 +64,9 @@ public EvaluationCell getCell(int rowIndex, int columnIndex) { // shortcut evaluation if reference is outside the bounds of existing data // see issue #61841 for impact on VLOOKUP in particular - if (rowIndex > _lastDefinedRow) return null; + if (rowIndex > getLastRowNum()) { + return null; + } // cache for performance: ~30% speedup due to caching if (_cellCache == null) { Index: src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFSheet.java =================================================================== --- src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFSheet.java (revision 1848483) +++ src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFSheet.java (working copy) @@ -165,6 +165,7 @@ protected CTWorksheet worksheet; private final SortedMap _rows = new TreeMap<>(); + private int _lastRowNum=0; private List hyperlinks; private ColumnHelper columnHelper; private CommentsTable sheetComments; @@ -263,6 +264,7 @@ private void initRows(CTWorksheet worksheetParam) { _rows.clear(); + _lastRowNum=0; tables = new TreeMap<>(); sharedFormulas = new HashMap<>(); arrayFormulas = new ArrayList<>(); @@ -782,6 +784,7 @@ XSSFRow r = new XSSFRow(ctRow, this); r.setRowNum(rownum); _rows.put(rownumI, r); + _lastRowNum = Math.max(_lastRowNum, rownum); return r; } @@ -1211,7 +1214,7 @@ @Override public int getLastRowNum() { - return _rows.isEmpty() ? 0 : _rows.lastKey(); + return _lastRowNum; } @Override @@ -2016,6 +2019,7 @@ // this is not the physical row number! final int idx = _rows.headMap(rowNumI).size(); _rows.remove(rowNumI); + _lastRowNum = _rows.isEmpty() ? 0 : _rows.lastKey(); worksheet.getSheetData().removeRow(idx); // also remove any comment located in that row @@ -3063,6 +3067,7 @@ final Integer rownumI = new Integer(r.getRowNum()); // NOSONAR _rows.put(rownumI, r); } + _lastRowNum = _rows.isEmpty() ? 0 : _rows.lastKey(); } // remove all rows which will be overwritten