PHPSpreadsheet: How to find last cell in worksheet

Viewed 11

According to the PHPSpreadsheet docs "Accessing cells in a Spreadsheet should be pretty straightforward." but the only references are to finding cells by cell coordinate such as:

$spreadsheet->getActiveSheet()
    ->getCell('B8')
    ->setValue('Some value');

What I am trying to do is something I thought would be simple and that is to locate the last cell with input and make that the active cell. I am finding references in SO and PHPSpreadsheet docs to an iterator like this:

foreach ($worksheet->getRowIterator() as $row) {
    echo '<tr>' . PHP_EOL;
    $cellIterator = $row->getCellIterator();
    $cellIterator->setIterateOnlyExistingCells(TRUE);

... but that seems like a lot just to find the last cell with input. Does anyone have any bright ideas on this? Is there any type of end-of-worksheet code in PHPSpreadsheet?

1 Answers

I use these lines:

// Get the highest row and column numbers referenced in the worksheet
$highestRow = $worksheet->getHighestRow(); // e.g. 10
$highestColumn = $worksheet->getHighestColumn(); // e.g 'F'
$highestColumnIndex = PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn);

$cellvalue = $worksheet->getCellByColumnAndRow($highestColumnIndex , $highestRow)
Related