Calculate widths for auto-size columns

@param  boolean  $calculateMergeCells  Calculate merge cell width
@return PHPExcel_Worksheet;
328072
public function calculateColumnWidths($calculateMergeCells = false)
    {
        // initialize $autoSizes array
        $autoSizes = array();
        foreach ($this->getColumnDimensions() as $colDimension) {
            if ($colDimension->getAutoSize()) {
                $autoSizes[$colDimension->getColumnIndex()] = -1;
            }
        }

        // There is only something to do if there are some auto-size columns
        if (!empty($autoSizes)) {

            // build list of cells references that participate in a merge
            $isMergeCell = array();
            foreach ($this->getMergeCells() as $cells) {
                foreach (PHPExcel_Cell::extractAllCellReferencesInRange($cells) as $cellReference) {
                    $isMergeCell[$cellReference] = true;
                }
            }

            // loop through all cells in the worksheet
            foreach ($this->getCellCollection(false) as $cellID) {
                $cell = $this->getCell($cellID);
				if (isset($autoSizes[$this->_cellCollection->getCurrentColumn()])) {
                    // Determine width if cell does not participate in a merge
					if (!isset($isMergeCell[$this->_cellCollection->getCurrentAddress()])) {
                        // Calculated value
                        // To formatted string
						$cellValue = PHPExcel_Style_NumberFormat::toFormattedString(
							$cell->getCalculatedValue(),
							$this->getParent()->getCellXfByIndex($cell->getXfIndex())->getNumberFormat()->getFormatCode()
						);

						$autoSizes[$this->_cellCollection->getCurrentColumn()] = max(
							(float) $autoSizes[$this->_cellCollection->getCurrentColumn()],
                            (float)PHPExcel_Shared_Font::calculateColumnWidth(
								$this->getParent()->getCellXfByIndex($cell->getXfIndex())->getFont(),
                                $cellValue,
								$this->getParent()->getCellXfByIndex($cell->getXfIndex())->getAlignment()->getTextRotation(),
                                $this->getDefaultStyle()->getFont()
                            )
                        );
                    }
                }
            }

            // adjust column widths
            foreach ($autoSizes as $columnIndex => $width) {
                if ($width == -1) $width = $this->getDefaultColumnDimension()->getWidth();
                $this->getColumnDimension($columnIndex)->setWidth($width);
            }
        }

        return $this;
    }
1373390
public function mergeCells($pRange = 'A1:A1')
    {
        // Uppercase coordinate
        $pRange = strtoupper($pRange);

        if (strpos($pRange,':') !== false) {
            $this->_mergeCells[$pRange] = $pRange;

            // make sure cells are created

            // get the cells in the range
            $aReferences = PHPExcel_Cell::extractAllCellReferencesInRange($pRange);

            // create upper left cell if it does not already exist
            $upperLeft = $aReferences[0];
            if (!$this->cellExists($upperLeft)) {
                $this->getCell($upperLeft)->setValueExplicit(null, PHPExcel_Cell_DataType::TYPE_NULL);
            }

            // create or blank out the rest of the cells in the range
            $count = count($aReferences);
            for ($i = 1; $i < $count; $i++) {
                $this->getCell($aReferences[$i])->setValueExplicit(null, PHPExcel_Cell_DataType::TYPE_NULL);
            }

        } else {
            throw new PHPExcel_Exception('Merge must be set on a range of cells.');
        }

        return $this;
    }
378144
public function checkMatrixDimensions($B = null) {
		if ($B instanceof PHPExcel_Shared_JAMA_Matrix) {
			if (($this->m == $B->getRowDimension()) && ($this->n == $B->getColumnDimension())) {
				return true;
			} else {
				throw new PHPExcel_Calculation_Exception(self::MatrixDimensionException);
			}
		} else {
			throw new PHPExcel_Calculation_Exception(self::ArgumentTypeException);
		}
	}
447383
protected function _calculateWidths($rows)
    {
        $widths = [];
        foreach ($rows as $line) {
            foreach (array_values($line) as $k => $v) {
                $columnLength = $this->_cellWidth($v);
                if ($columnLength >= (isset($widths[$k]) ? $widths[$k] : 0)) {
                    $widths[$k] = $columnLength;
                }
            }
        }

        return $widths;
    }
295552
public function getMergedCellsCount()
    {
        //check whether workshett name is set or not
        if ($this->worksheetName == '')
            throw new Exception('Worksheet name not specified');
        $strURI = Product::$baseProductUri . '/cells/' . $this->getFileName() .
            '/worksheets/' . $this->worksheetName . '/mergedCells';
        $signedURI = Utils::sign($strURI);
        $responseStream = Utils::processCommand($signedURI, 'GET', '', '');
        $json = json_decode($responseStream);
        return $json->MergedCells->Count;

    }
490534
private function getCellWidth($cell)
    {
        $lineWidths = [0];
        foreach (explode(PHP_EOL, $cell) as $line) {
            $lineWidths[] = Helper::strlenWithoutDecoration($this->outputCopy->getFormatter(), $line);
        }
        $cellWidth = max($lineWidths);
        if ($cell instanceof TableCell && $cell->getColspan() > 1) {
            $cellWidth /= $cell->getColspan();
        }

        return $cellWidth;
    }
324890
public function getCellWidth($fontName, $fontSize, $value)
    {
        $width = 1;
        foreach ($this->getSingleCharacterArray($value) as $char) {
            $width += $this->getCharacterWidth($fontName, $fontSize, $char);
        }

        return $width;
    }
449881
public static function setTextAreaSize($options)
    {
        if (isset($options['size'])) {
            return self::setQuickTextAreaSize($options);
        }

        $cols = array_get($options, 'cols', 50);
        $rows = array_get($options, 'rows', 10);

        return array_merge($options, compact('cols', 'rows'));
    }
894546
function mergeSize(size, result) {
            if (size) {
                if (size.hasOwnProperty("scale")) {
                    result.scale = size.scale;
                }

                if (size.hasOwnProperty("width")) {
                    result.width = size.width;
                }

                if (size.hasOwnProperty("widthUnit")) {
                    result.widthUnit = size.widthUnit;
                }

                if (size.hasOwnProperty("height")) {
                    result.height = size.height;
                }

                if (size.hasOwnProperty("heightUnit")) {
                    result.heightUnit = size.heightUnit;
                }
            }
        }
54467
public void setCellMerge(final int colIndex, final int rowMerge, final int columnMerge) throws IOException {
        if (rowMerge <= 0 || columnMerge <= 0) return;
        if (rowMerge <= 1 && columnMerge <= 1) return;

        this.parent.setCellMerge(this.rowIndex, colIndex, rowMerge, columnMerge);
    }
168508
public function autoSize($minRows = false, $maxRows = null)
    {

        $this->props['autosize'] = $maxRows === null ? boolval($minRows) : compact('minRows', 'maxRows');
        return $this;
    }
73682
protected function calculateColumnWidthPercent(array $columns)
    {
        $widthAllColumn = 0;
        foreach ($columns as $column) {
            /* @var $column \ZfcDatagrid\Column\AbstractColumn */
            $widthAllColumn += $column->getWidth();
        }

        $widthSum = 0;
        // How much 1 percent columnd width is really "one" percent...
        $relativeOnePercent = $widthAllColumn / 100;

        foreach ($columns as $column) {
            $widthSum += (($column->getWidth() / $relativeOnePercent));
            $column->setWidth(($column->getWidth() / $relativeOnePercent));
        }
    }
905416
private void sameValueMergeRows(MergeRow mergeRowAnn, int itemSize, Cell fromCell) {
        String lastValue = PoiUtil.getCellStringValue(fromCell);
        int preRow = fromCell.getRowIndex();
        val col = fromCell.getColumnIndex();
        int i = preRow + 1;

        for (final int ii = preRow + itemSize; i < ii; ++i) {
            val cell = sheet.getRow(i).getCell(col);
            val cellValue = PoiUtil.getCellStringValue(cell);
            if (StringUtils.equals(cellValue, lastValue)) continue;

            directMergeRows(mergeRowAnn, preRow, i - 1, col);
            lastValue = cellValue;
            preRow = i;
        }

        directMergeRows(mergeRowAnn, preRow, i - 1, col);
    }
1230950
public function unmergeCells($pRange = 'A1:A1')
    {
        // Uppercase coordinate
        $pRange = strtoupper($pRange);

        if (strpos($pRange, ':') !== false) {
            if (isset($this->mergeCells[$pRange])) {
                unset($this->mergeCells[$pRange]);
            } else {
                throw new PHPExcel_Exception('Cell range ' . $pRange . ' not known as merged.');
            }
        } else {
            throw new PHPExcel_Exception('Merge can only be removed from a range of cells.');
        }

        return $this;
    }
290346
public static int mergingCells(Sheet sheet, int firstRow, int lastRow, int firstColumn, int lastColumn, CellStyle cellStyle) {
		final CellRangeAddress cellRangeAddress = new CellRangeAddress(//
				firstRow, // first row (0-based)
				lastRow, // last row (0-based)
				firstColumn, // first column (0-based)
				lastColumn // last column (0-based)
		);

		if (null != cellStyle) {
			RegionUtil.setBorderTop(cellStyle.getBorderTopEnum(), cellRangeAddress, sheet);
			RegionUtil.setBorderRight(cellStyle.getBorderRightEnum(), cellRangeAddress, sheet);
			RegionUtil.setBorderBottom(cellStyle.getBorderBottomEnum(), cellRangeAddress, sheet);
			RegionUtil.setBorderLeft(cellStyle.getBorderLeftEnum(), cellRangeAddress, sheet);
		}
		return sheet.addMergedRegion(cellRangeAddress);
	}
1064589
public static int checkNestedMergedSizeRecords(final Sheet sheet, final List<MergedRecord> records) 
            throws NestedRecordMergedSizeException {
        
        int mergedSize = -1;
        
        for(MergedRecord record : records) {
            
            if(mergedSize < 0) {
                mergedSize = record.getMergedSize();
                continue;
            }
            
            if(mergedSize != record.getMergedSize()) {
                
                String message = MessageBuilder.create("anno.XlsNestedRecords.mergeSizeNoMatch")
                        .var("sheetName", sheet.getSheetName())
                        .var("address", record.getMergedRange().formatAsString())
                        .var("actualMergeSize", record.getMergedSize())
                        .var("expectedMergeSize", mergedSize)
                        .format();
                throw new NestedRecordMergedSizeException(sheet.getSheetName(), record.getMergedSize(), message);
            }
        }
        
        return mergedSize;
        
    }
1252474
protected function getColumnWidths(array $columnNames, array $rows): array
	{
		$columnWidths = [];

		// First we'll get the width of the column names

		foreach(array_values($columnNames) as $key => $value)
		{
			$columnWidths[$key] = $this->stringWidthWithoutFormatting($value);
		}

		// Then we'll go through each row and check if the cells are wider than the column names

		foreach($rows as $row)
		{
			foreach(array_values($row) as $key => $value)
			{
				$width = $this->stringWidthWithoutFormatting($value);

				if($width > $columnWidths[$key])
				{
					$columnWidths[$key] = $width;
				}
			}
		}

		// Return array of column widths

		return $columnWidths;
	}