PHPExcel Column Loop

后端 未结 7 1977
Happy的楠姐
Happy的楠姐 2020-12-04 14:49

How can I do a loop which based on Excel worksheet columns? I found (and used) WorksheetIterator, RowIterator and CellIterator but nothing about columns.

7条回答
  •  眼角桃花
    2020-12-04 15:11

    This short snippet provides loop throught rows of columns. It gets the indexes of last non empty column (and its row) and loops to that indexes, so be aware of forgotten values in excel.

    Code loops throught rows of column A, then rows of column B ...

    $objReader = new PHPExcel_Reader_Excel2007();
    $objReader->setReadDataOnly(true);
    $objPHPExcel = $objReader->load($file);
    
    foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) 
    {
        $worksheetTitle = $worksheet->getTitle();
        $highestColumn = $worksheet->getHighestColumn();
        $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
    
        // expects same number of row records for all columns
        $highestRow = $worksheet->getHighestRow();
    
        for($col = 0; $col < $highestColumnIndex; $col++)
        {
            // if you do not expect same number of row records for all columns
            // get highest row index for each column
            // $highestRow = $worksheet->getHighestRow();
    
            for ($row = 1; $row <= $highestRow; $row++)
            {
                $cell = $worksheet->getCellByColumnAndRow($col, $row);
                $val = $cell->getValue();
                // do what you want with cell value
            }
        }
    }
    

提交回复
热议问题