在 Excel 中搜索 PHP

Searching in Excel with PHP

我正在尝试使用 PHPExcel 通过第一个单元格值查找 Excel table 中一行的最后一个单元格值。用户输入行中第一个单元格的值(即 "command" 参数),如果它存在于 table 中,我的函数应该跳转到行中的最后一个单元格并且 return 值。这是我的代码:

public function search($command, $excelobj) {
    foreach ($excelobj->getWorksheetIterator() as $worksheet) {
        foreach ($worksheet->getRowIterator() as $row) {
            $rowiterator = $worksheet->getRowIterator();
            foreach ($row->getCellIterator() as $cell) {
                $celliterator = $row->getCellIterator();
                $head = $celliterator->current()->getValue();
                if(strcmp($head, $command)) {
                    for ($i = 0; $i == 8; $i++) {
                        $celliterator->next();
                    }
                    return $cell->getValue();
                }
            }
        }
    }
    return false;
}

出于某种原因,它总是 return 错误。

我自己解决了,这段代码运行正常:

public function search($command, $excelobj) {
    foreach ($excelobj->getWorksheetIterator() as $worksheet) {
        foreach ($worksheet->getRowIterator() as $row) {
            $rowiterator = $worksheet->getRowIterator();
            $celliterator = $row->getCellIterator();
            $celliterator->setIterateOnlyExistingCells(true);
            $head = $celliterator->current()->getValue();
            while (strcmp($head, $command) !== 0 && $rowiterator->valid()) {
                $rowiterator->next();
                $row = new PHPExcel_Worksheet_Row($worksheet, $rowiterator->key());
                $celliterator = $row->getCellIterator();
                $head = $celliterator->current()->getValue();
            }
            for ($i = 0; $i <= 7; $i++) {
                $celliterator->next();
            }
            return $celliterator->current()->getValue();
        }
    }
    return false;
}