diff --git a/src/Spout/Reader/Common/Manager/RowManager.php b/src/Spout/Reader/Common/Manager/RowManager.php index 623c8d8..67c8fb1 100644 --- a/src/Spout/Reader/Common/Manager/RowManager.php +++ b/src/Spout/Reader/Common/Manager/RowManager.php @@ -56,12 +56,25 @@ class RowManager $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; } } diff --git a/tests/Spout/Reader/XLSX/ReaderTest.php b/tests/Spout/Reader/XLSX/ReaderTest.php index af7ca37..5b155b4 100644 --- a/tests/Spout/Reader/XLSX/ReaderTest.php +++ b/tests/Spout/Reader/XLSX/ReaderTest.php @@ -692,13 +692,29 @@ class ReaderTest extends TestCase $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 diff --git a/tests/resources/xlsx/sheet_with_empty_cells.xlsx b/tests/resources/xlsx/sheet_with_empty_cells.xlsx index d815a1c..8de9522 100644 Binary files a/tests/resources/xlsx/sheet_with_empty_cells.xlsx and b/tests/resources/xlsx/sheet_with_empty_cells.xlsx differ diff --git a/tests/resources/xlsx/sheet_with_empty_cells_without_dimensions.xlsx b/tests/resources/xlsx/sheet_with_empty_cells_without_dimensions.xlsx new file mode 100644 index 0000000..533a634 Binary files /dev/null and b/tests/resources/xlsx/sheet_with_empty_cells_without_dimensions.xlsx differ