Skip to content

PHPExcel Column Loop

To loop through cells in PHPExcel, you can use the following code snippet as an example:

Example of looping through cells in PHPExcel

php
<?php

require_once 'PHPExcel/IOFactory.php';

$inputFileName = 'example.xlsx';
$objPHPExcel = PHPExcel_IOFactory::load($inputFileName);

$worksheet = $objPHPExcel->getActiveSheet();

foreach ($worksheet->getRowIterator() as $row) {
  $cellIterator = $row->getCellIterator();
  $cellIterator->setIterateOnlyExistingCells(false);
  foreach ($cellIterator as $cell) {
    echo $cell->getValue() . "\n";
  }
}
![Watch a course](https://www.w3docs.com/images/svg/youtube.svg) [Learn object oriented PHP](https://www.w3docs.com/nx/course/learn-object-oriented-php)

This code uses the getRowIterator() method to loop through each row in the worksheet, and the getCellIterator() method to loop through each cell in the row. The setIterateOnlyExistingCells(false) method is used to ensure that the loop includes all cells, even if they are empty. The getValue() method is then used to access the value of each cell. To retrieve the column letter or index, you can use $cell->getColumn() or $cell->getColumnIndex().

Note: PHPExcel is deprecated. For modern projects, consider using PhpSpreadsheet, which provides a similar API.

Dual-run preview — compare with live Symfony routes.