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

Commit

Permalink
Skipped cells are in wrong order
Browse files Browse the repository at this point in the history
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'}`).
  • Loading branch information
adrilo committed May 14, 2021
1 parent fde8a49 commit 76017f0
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 1 deletion.
13 changes: 13 additions & 0 deletions src/Spout/Reader/Common/Manager/RowManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,12 +56,25 @@ public function fillMissingIndexesWithEmptyCells(Row $row)
$rowCells = $row->getCells();
$maxCellIndex = $numCells;

// If the row has empty cells, calling "setCellAtIndex" will add the cell
// but in the wrong place (the new cell is added at the end of the array).
// Therefore, we need to sort the array using keys to have proper order.
// @see https://github.com/box/spout/issues/740
$needsSorting = false;

for ($cellIndex = 0; $cellIndex < $maxCellIndex; $cellIndex++) {
if (!isset($rowCells[$cellIndex])) {
$row->setCellAtIndex($this->entityFactory->createCell(''), $cellIndex);
$needsSorting = true;
}
}

if ($needsSorting) {
$rowCells = $row->getCells();
ksort($rowCells);
$row->setCells($rowCells);
}

return $row;
}
}
18 changes: 17 additions & 1 deletion tests/Spout/Reader/XLSX/ReaderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -692,13 +692,29 @@ public function testReadShouldCreateOutputEmptyCellPreserved()
$allRows = $this->getAllRowsForFile('sheet_with_empty_cells.xlsx');

$expectedRows = [
['A', 'B', 'C'],
['A', '', 'C'],
['0', '', ''],
['1', '1', ''],
];
$this->assertEquals($expectedRows, $allRows, 'There should be 3 rows, with equal length');
}

/**
* https://github.com/box/spout/issues/184
* @return void
*/
public function testReadShouldCreateOutputEmptyCellPreservedWhenNoDimensionsSpecified()
{
$allRows = $this->getAllRowsForFile('sheet_with_empty_cells_without_dimensions.xlsx');

$expectedRows = [
['A', '', 'C'],
['0'],
['1', '1'],
];
$this->assertEquals($expectedRows, $allRows);
}

/**
* https://github.com/box/spout/issues/195
* @return void
Expand Down
Binary file modified tests/resources/xlsx/sheet_with_empty_cells.xlsx
Binary file not shown.
Binary file not shown.

0 comments on commit 76017f0

Please sign in to comment.