将Excel行读取为数组:PHPExcel是否有类似于fgetcsv()的函数?

6

我正在使用PHPExcel库重新编写一些CSV读取代码,但在遍历数据表时遇到了问题。

我的代码:

$filetype = PHPExcel_IOFactory::identify($filename);
$objReader = PHPExcel_IOFactory::createReader($filetype);
$xl = $objReader->load($filename);
$objWorksheet = $xl->getActiveSheet();

foreach($objWorksheet->getRowIterator() as  $rowIndex => $row){
    print_r($row);
}

我不希望在迭代之前将整个工作表转换为数组,因为我的一些Excel文件可能非常大,我宁愿避免大量的内存使用。
期望:$row返回该行中所有单元格的数组。
结果:$row是一个PHPExcel对象,其中包含该行中的单元格。
是否有一个与fgetcsv()相当的PHPExcel等效函数可以让我获取行中所有单元格的数组?
1个回答

13

是的,当你使用行迭代器时,它会依次返回一个PHPExcel_Worksheet_Row对象;然后你可以使用单元格迭代器(参见/Example/28iterator.php)迭代该行对象 ($row)。

foreach($objWorksheet->getRowIterator() as $row) {
    $cellIterator = $row->getCellIterator();
    $cellIterator->setIterateOnlyExistingCells(true);
    // Iterate over the individual cells in the row
    foreach ($cellIterator as $cell) {
        // Display information about the cell object
        echo 'I am Cell ' , $cell->getCoordinate() , PHP_EOL;
        echo '    and my value is ' , $cell->getValue() , PHP_EOL;
    }
}

或者,您可以将该行转换为数组,而不是使用单元格迭代器

$lastColumn = $objWorksheet->getHighestColumn();
foreach($objWorksheet->getRowIterator() as $rowIndex => $row) {
    // Convert the cell data from this row to an array of values
    //    just as though you'd retrieved it using fgetcsv()
    $array = $objWorksheet->rangeToArray('A'.$rowIndex.':'.$lastColumn.$rowIndex);
}

由于$array仅仅是一个单行中单元格的数组,所以它占用的内存与使用fgetcsv()函数检索一行的内存相同。


1
太棒了,第二个版本就是我想要的! - caitlin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接