Skip to content

Commit 275b948

Browse files
authored
Merge pull request #4069 from mogic-le/yield-docs
Documentation and example for rangeToArrayYieldRows()
2 parents 60baa3a + 1c931e2 commit 275b948

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

docs/topics/Looping the Loop.md

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -308,6 +308,28 @@ But a peak memory usage of 49,152KB compared with the 57,344KB used by `toArray(
308308
Like `toArray()`, `rangeToArray()` is easy to use, but it has the same limitations for flexibility. It provides the same limited control over how the data from each cell is returned in the array as `toArray()`.
309309
The same additional arguments that can be provided for the `toArray()` method can also be provided to `rangeToArray()`.
310310

311+
312+
## Using `rangeToArrayYieldRows()`
313+
314+
Since v2.1.0 the worksheet method `rangeToArrayYieldRows()` is available.
315+
It allows you to iterate over all sheet's rows with little memory consumption,
316+
while obtaining each row as an array:
317+
318+
```php
319+
$rowGenerator = $sheet->rangeToArrayYieldRows(
320+
'A1:' . $sheet->getHighestDataColumn() . $sheet->getHighestDataRow(),
321+
null,
322+
false,
323+
false
324+
);
325+
foreach ($rowGenerator as $row) {
326+
echo $row[0] . ' | ' . $row[1] . "\n";
327+
}
328+
```
329+
330+
See `samples/Reader2/23_iterateRowsYield.php`.
331+
332+
311333
## Using Iterators
312334

313335
You don't need to build an array from the worksheet to loop through the rows and columns and do whatever processing you need; you can loop through the rows and columns in the Worksheet directly and more efficiently using PhpSpreadsheet's built-in iterators.
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
<?php
2+
3+
/**
4+
* Use rangeToArrayYieldRows() to efficiently iterate over all rows.
5+
*/
6+
7+
require __DIR__ . '/../Header.php';
8+
9+
$inputFileName = __DIR__ . '/../Reader/sampleData/example1.xls';
10+
11+
$spreadsheet = PhpOffice\PhpSpreadsheet\IOFactory::load(
12+
$inputFileName,
13+
PhpOffice\PhpSpreadsheet\Reader\IReader::READ_DATA_ONLY
14+
);
15+
$sheet = $spreadsheet->getSheet(0);
16+
17+
$rowGenerator = $sheet->rangeToArrayYieldRows(
18+
$spreadsheet->getActiveSheet()->calculateWorksheetDataDimension(),
19+
null,
20+
false,
21+
false
22+
);
23+
foreach ($rowGenerator as $row) {
24+
echo '| ' . $row[0] . ' | ' . $row[1] . "|\n";
25+
}

0 commit comments

Comments
 (0)