Looping through worksheets with PHPExcel

user717236 picture user717236 · Jul 23, 2012 · Viewed 35.2k times · Source

I'm using the PHPExcel library to read an Excel file and perform processing on it. I want to loop through each worksheet. I checked the documentation and all I could find was changing the active worksheet index or only loading specified worksheets. How can I loop through all worksheets?

Thank you for any help.

Here is the documentation's looping example, for reference:

<?php
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objReader->setReadDataOnly(true);

$objPHPExcel = $objReader->load("test.xlsx");
$objWorksheet = $objPHPExcel->getActiveSheet();

echo '<table>' . "\n";
foreach ($objWorksheet->getRowIterator() as $row) {
  echo '<tr>' . "\n";

  $cellIterator = $row->getCellIterator();
  $cellIterator->setIterateOnlyExistingCells(false); // This loops all cells,
                                                     // even if it is not set.
                                                     // By default, only cells
                                                     // that are set will be
                                                     // iterated.
  foreach ($cellIterator as $cell) {
    echo '<td>' . $cell->getValue() . '</td>' . "\n";
  }

  echo '</tr>' . "\n";
}
echo '</table>' . "\n";
?>

Answer

jeffery_the_wind picture jeffery_the_wind · Jul 23, 2012

I think you can do this. Increment the active sheet until there aren't any left, then do what you want with each one:

<?php

    $objReader = PHPExcel_IOFactory::createReader('Excel2007');
    $objReader->setReadDataOnly(true);

    $objPHPExcel = $objReader->load("test.xlsx");

    $i = 0;
    while ($objPHPExcel->setActiveSheetIndex($i)){

        $objWorksheet = $objPHPExcel->getActiveSheet();
        //now do whatever you want with the active sheet
        ...
        $i++;

    }

    ...

?>