Looping through worksheets with PHPExcel

偶尔善良 提交于 2019-12-03 01:37:21

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

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++;

    }

    ...

?>

Here's a useful function I use for iterating over sheets and returning an array of cell values for each with the sheet title as array key:

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());
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!