且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用PHPExcel循环工作表

更新时间:2023-11-25 15:19:28

您正在使用迭代器。你看了/ Tests目录中迭代器的代码示例吗?如果是这样,您可能已经看到了WorksheetIterator的引用。另外,PHPExcel对象的getAllSheets()方法返回一个工作表数组,它允许您使用一个foreach循环


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";
?>

You're using iterators. Did you look at the code example for iterators in the /Tests directory? If so, you might have seen reference to the WorksheetIterator

Alternatively, the getAllSheets() method of the PHPExcel object returns an array of worksheets, which allows you to use a foreach loop