/** * Calculate an (approximate) OpenXML column width, based on font size and text contained * * @param \PHPExcel\Style\Font $font Font object * @param \PHPExcel\RichText|string $cellText Text to calculate width * @param integer $rotation Rotation angle * @param \PHPExcel\Style\Font|NULL $defaultFont Font object * @return integer Column width */ public static function calculateColumnWidth(\PHPExcel\Style\Font $font, $cellText = '', $rotation = 0, \PHPExcel\Style\Font $defaultFont = null) { // If it is rich text, use plain text if ($cellText instanceof \PHPExcel\RichText) { $cellText = $cellText->getPlainText(); } // Special case if there are one or more newline characters ("\n") if (strpos($cellText, "\n") !== false) { $lineTexts = explode("\n", $cellText); $lineWidths = array(); foreach ($lineTexts as $lineText) { $lineWidths[] = self::calculateColumnWidth($font, $lineText, $rotation = 0, $defaultFont); } return max($lineWidths); // width of longest line in cell } // Try to get the exact text width in pixels $approximate = self::$autoSizeMethod == self::AUTOSIZE_METHOD_APPROX; if (!$approximate) { $columnWidthAdjust = ceil(self::getTextWidthPixelsExact('n', $font, 0) * 1.07); try { // Width of text in pixels excl. padding // and addition because Excel adds some padding, just use approx width of 'n' glyph $columnWidth = self::getTextWidthPixelsExact($cellText, $font, $rotation) + $columnWidthAdjust; } catch (\PHPExcel\Exception $e) { $approximate = true; } } if ($approximate) { $columnWidthAdjust = self::getTextWidthPixelsApprox('n', $font, 0); // Width of text in pixels excl. padding, approximation // and addition because Excel adds some padding, just use approx width of 'n' glyph $columnWidth = self::getTextWidthPixelsApprox($cellText, $font, $rotation) + $columnWidthAdjust; } // Convert from pixel width to column width $columnWidth = Drawing::pixelsToCellDimension($columnWidth, $defaultFont); // Return return round($columnWidth, 6); }