SpreadSheet-Coding.com

PHPSpreadsheet · Google Sheets API · Excel

Spreadsheets, driven by code.

Hands-on PHP tutorials for working with Excel and Google Sheets — read and write .xlsx, convert files to JSON, stream downloads in the browser, and insert images, formulas, and styling. Every guide ships with code you can copy, run, and adapt.

iterate-cells.php View article
<?php

require 'vendor/autoload.php';

use \PhpOffice\PhpSpreadsheet\IOFactory;

$spreadsheet = IOFactory::load('inventory.xlsx');
$worksheet = $spreadsheet->getActiveSheet();

// Row 3 of this sheet has no value in column B.
echo 'B3 exists at the start? ' . var_export($worksheet->cellExists('B3'), true) . "\n";

// Only the cells that were actually given a value.
echo "\nIterating existing cells only:\n";

foreach ($worksheet->getRowIterator(2) as $row) {
    $cells = $row->getCellIterator();
    $cells->setIterateOnlyExistingCells(true);

    $line = [];
    foreach ($cells as $cell) {
        $line[] = $cell->getCoordinate() . '=' . var_export($cell->getValue(), true);
    }

    echo '  row ' . $row->getRowIndex() . ': ' . implode('  ', $line) . "\n";
}

echo "\nB3 exists now? " . var_export($worksheet->cellExists('B3'), true) . "\n";

// The default: every cell in the row's range, gaps included.
echo "\nIterating the whole range (the default):\n";

foreach ($worksheet->getRowIterator(2) as $row) {
    $cells = $row->getCellIterator();
    $cells->setIterateOnlyExistingCells(false);

    $line = [];
    foreach ($cells as $cell) {
        $line[] = $cell->getCoordinate() . '=' . var_export($cell->getValue(), true);
    }

    echo '  row ' . $row->getRowIndex() . ': ' . implode('  ', $line) . "\n";
}

// Walking the gaps did not just report them - it created them.
echo "\nB3 exists after the full-range walk? "
    . var_export($worksheet->cellExists('B3'), true) . "\n";

// What an iterator can do that toArray() cannot: stop early.
echo "\nStopping at the first row with qty under 10:\n";

foreach ($worksheet->getRowIterator(2) as $row) {
    $qty = $worksheet->getCell('C' . $row->getRowIndex())->getValue();

    if ($qty < 10) {
        echo '  row ' . $row->getRowIndex() . ' has qty ' . $qty . " - stopping.\n";
        break;
    }

    echo '  row ' . $row->getRowIndex() . " ok.\n";
}

The full script from Loop Through Cells With Iterators In PHP Using PHPSpreadSheet — copy, run, adapt.

IOFactory::load() PhpSpreadsheet
Open any spreadsheet file
getActiveSheet() PhpSpreadsheet
Select the worksheet to fill
fromArray() PhpSpreadsheet
Write many rows at once
getCalculatedValue() PhpSpreadsheet
Read a formula result
save('php://output') PhpSpreadsheet
Stream the file as a download
spreadsheets_values->get() Google Sheets
Read a range of cells
spreadsheets_values->update() Google Sheets
Write a range of cells
spreadsheets->create() Google Sheets
Create a new spreadsheet
json_encode() PHP
Serialize rows to JSON
header() PHP
Send the download headers