Looping through worksheets with PHPExcel

前端 未结 3 914
情深已故
情深已故 2021-02-05 08:07

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

相关标签:
3条回答
  • 2021-02-05 08:22

    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

    0 讨论(0)
  • 2021-02-05 08:28

    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());
        }
    }
    
    0 讨论(0)
  • 2021-02-05 08:40

    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++;
    
        }
    
        ...
    
    ?>
    
    0 讨论(0)
提交回复
热议问题