PHPExcel列循环 [英] PHPExcel Column Loop

查看:687
本文介绍了PHPExcel列循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何执行基于Excel工作表列的循环?我找到了(并使用了)WorksheetIterator,RowIterator和CellIterator,但是关于列却一无所获.

解决方案

没有ColumnIterator,因此您必须手工完成.

对于任何给定的工作表:

要循环某列的行:

$column = 'A';
$lastRow = $worksheet->getHighestRow();
for ($row = 1; $row <= $lastRow; $row++) {
    $cell = $worksheet->getCell($column.$row);
    //  Do what you want with the cell
}

要连续循环各列,您可以利用PHP的Perls样式功能来增加字符:

$row = 1;
$lastColumn = $worksheet->getHighestColumn();
$lastColumn++;
for ($column = 'A'; $column != $lastColumn; $column++) {
    $cell = $worksheet->getCell($column.$row);
    //  Do what you want with the cell
}

请注意,在比较列字母以测试循环中的最后一列时,我们不能简单地使用<或< =,因为我们要比较字符串,而在标准字符串比较中是"B">"AZ",所以我们使用!=比较,将最高列值递增,以使第一列ID超过终点. /p>

您也可以使用

$worksheet->cellExists($column.$row);

在循环中测试单元的存在,然后使用getCell()(或不通过它)模拟迭代器getIterateOnlyExistingCells()行为来访问它

迭代器实际上相当慢,因此您很可能会发现这些简单的循环比使用迭代器要快.

更新(2015-05-06)

PHPExcel版本1.8.1引入了新的列迭代器.行和列迭代器还允许您指定要迭代的行或列的范围,并允许您在遍历时使用prev()和next()

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

解决方案

There is no ColumnIterator, so you'll have to do this by hand.

For any given worksheet:

To loop rows for a column:

$column = 'A';
$lastRow = $worksheet->getHighestRow();
for ($row = 1; $row <= $lastRow; $row++) {
    $cell = $worksheet->getCell($column.$row);
    //  Do what you want with the cell
}

To loop columns in a row, you can take advantage of PHP's Perls-style ability to increment characters:

$row = 1;
$lastColumn = $worksheet->getHighestColumn();
$lastColumn++;
for ($column = 'A'; $column != $lastColumn; $column++) {
    $cell = $worksheet->getCell($column.$row);
    //  Do what you want with the cell
}

Note that when comparing column letters to test for the last column in the loop, we can't simply use < or <= because we're comparing strings, and "B" > "AZ" in standard string comparison, so we use a != comparison, having incremented the highest column value to give the first column ID past the end point.

You can also use

$worksheet->cellExists($column.$row);

in the loop to test for the existence of a cell before accessing it using getCell() (or not) to emulate the iterator getIterateOnlyExistingCells() behaviour

The iterators are actually fairly slow, so you may well find these simple loops are faster than using the iterators.

UPDATE (2015-05-06)

PHPExcel version 1.8.1 has introduced a new Column Iterator. The Row and Column iterators also allows you to specify a range of rows or columns to iterate, and allow you to use prev() and well as next() when looping through

这篇关于PHPExcel列循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆