我正在使用PHPExcel库来读取Excel文件并对其执行处理。我想遍历每个工作表。我检查了文档,我找到的只是更改活动工作表索引或仅加载指定的工作表。我如何遍历所有工作表?
感谢您的帮助。
以下是文档的循环示例,供参考:
<?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";
?>
答案 0 :(得分:15)
我认为你可以做到这一点。增加活动表直到没有任何剩余,然后对每个执行所需的操作:
<?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++;
}
...
?>
答案 1 :(得分:11)
您正在使用迭代器。您是否在/ Tests目录中查看了迭代器的代码示例?如果是这样,您可能已经看到了对WorksheetIterator的引用
或者,PHPExcel对象的getAllSheets()方法返回一个工作表数组,允许您使用foreach循环
答案 2 :(得分:10)
这是一个有用的函数,我用它来迭代工作表并为每个工作表返回一个单元格值数组,并将工作表标题作为数组键:
function getSheets($fileName) {
try {
$fileType = PHPExcel_IOFactory::identify($fileName);
$objReader = PHPExcel_IOFactory::createReader($fileType);
$objPHPExcel = $objReader->load($fileName);
$sheets = [];
foreach ($objPHPExcel->getAllSheets() as $sheet) {
$sheets[$sheet->getTitle()] = $sheet->toArray();
}
return $sheets;
} catch (Exception $e) {
die($e->getMessage());
}
}