From 939f24ecb4256a357384e57c4bfaba57b3ed6727 Mon Sep 17 00:00:00 2001 From: tomaszsita Date: Thu, 24 Nov 2016 10:37:51 +0000 Subject: [PATCH] Calculate column auto width for merged cells (if horizontal, 1-column wide merge only) This is to fix the situation when cells merged vertically are ignored in columns auto size calculations. I also removed $calculateMergeCells param as it wasn't used and I believe the only situation when you want to calculate the width of merged columns has been covered here (and there's no reason to not calculate it). FIX #46 --- src/PhpSpreadsheet/Worksheet.php | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/src/PhpSpreadsheet/Worksheet.php b/src/PhpSpreadsheet/Worksheet.php index 044cb9f3..b725cbe8 100644 --- a/src/PhpSpreadsheet/Worksheet.php +++ b/src/PhpSpreadsheet/Worksheet.php @@ -701,10 +701,9 @@ class Worksheet implements IComparable /** * Calculate widths for auto-size columns * - * @param bool $calculateMergeCells Calculate merge cell width * @return Worksheet; */ - public function calculateColumnWidths($calculateMergeCells = false) + public function calculateColumnWidths() { // initialize $autoSizes array $autoSizes = []; @@ -728,8 +727,23 @@ class Worksheet implements IComparable foreach ($this->getCellCollection(false) as $cellID) { $cell = $this->getCell($cellID, false); if ($cell !== null && isset($autoSizes[$this->cellCollection->getCurrentColumn()])) { - // Determine width if cell does not participate in a merge - if (!isset($isMergeCell[$this->cellCollection->getCurrentAddress()])) { + //Determine if cell is in merge range + $isMerged = isset($isMergeCell[$this->cellCollection->getCurrentAddress()]); + + //By default merged cells should be ignored + $isMergedButProceed = false; + + //The only exception is if it's a merge range value cell of a 'vertical' randge (1 column wide) + if ($isMerged && $cell->isMergeRangeValueCell()) { + $range = $cell->getMergeRange(); + $rangeBoundaries = Cell::rangeDimension($range); + if ($rangeBoundaries[0] == 1) { + $isMergedButProceed = true; + } + } + + // Determine width if cell does not participate in a merge or does and is a value cell of 1-column wide range + if (!$isMerged || $isMergedButProceed) { // Calculated value // To formatted string $cellValue = Style\NumberFormat::toFormattedString(