Skip to content
This repository was archived by the owner on May 26, 2022. It is now read-only.

Commit 76017f0

Browse files
committed
Skipped cells are in wrong order
This only happens when no sheet's dimension is specified. When filling empty cells with empty strings, we push these new cells with the correct cell index but they are added at the end of the cells array (normal PHP behavior). This means that we were going from `{[0] => 'A', [2] => 'C'}` to `{[0] => 'A', [2] => 'C', [1] => ''}`. We therefore need to sort the array to get the values in the correct order ( `{[0] => 'A', [1] => '', [2] => 'C'}`).
1 parent fde8a49 commit 76017f0

File tree

4 files changed

+30
-1
lines changed

4 files changed

+30
-1
lines changed

src/Spout/Reader/Common/Manager/RowManager.php

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,12 +56,25 @@ public function fillMissingIndexesWithEmptyCells(Row $row)
5656
$rowCells = $row->getCells();
5757
$maxCellIndex = $numCells;
5858

59+
// If the row has empty cells, calling "setCellAtIndex" will add the cell
60+
// but in the wrong place (the new cell is added at the end of the array).
61+
// Therefore, we need to sort the array using keys to have proper order.
62+
// @see https://github.com/box/spout/issues/740
63+
$needsSorting = false;
64+
5965
for ($cellIndex = 0; $cellIndex < $maxCellIndex; $cellIndex++) {
6066
if (!isset($rowCells[$cellIndex])) {
6167
$row->setCellAtIndex($this->entityFactory->createCell(''), $cellIndex);
68+
$needsSorting = true;
6269
}
6370
}
6471

72+
if ($needsSorting) {
73+
$rowCells = $row->getCells();
74+
ksort($rowCells);
75+
$row->setCells($rowCells);
76+
}
77+
6578
return $row;
6679
}
6780
}

tests/Spout/Reader/XLSX/ReaderTest.php

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -692,13 +692,29 @@ public function testReadShouldCreateOutputEmptyCellPreserved()
692692
$allRows = $this->getAllRowsForFile('sheet_with_empty_cells.xlsx');
693693

694694
$expectedRows = [
695-
['A', 'B', 'C'],
695+
['A', '', 'C'],
696696
['0', '', ''],
697697
['1', '1', ''],
698698
];
699699
$this->assertEquals($expectedRows, $allRows, 'There should be 3 rows, with equal length');
700700
}
701701

702+
/**
703+
* https://github.com/box/spout/issues/184
704+
* @return void
705+
*/
706+
public function testReadShouldCreateOutputEmptyCellPreservedWhenNoDimensionsSpecified()
707+
{
708+
$allRows = $this->getAllRowsForFile('sheet_with_empty_cells_without_dimensions.xlsx');
709+
710+
$expectedRows = [
711+
['A', '', 'C'],
712+
['0'],
713+
['1', '1'],
714+
];
715+
$this->assertEquals($expectedRows, $allRows);
716+
}
717+
702718
/**
703719
* https://github.com/box/spout/issues/195
704720
* @return void
-97 Bytes
Binary file not shown.
Binary file not shown.

0 commit comments

Comments
 (0)