Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

phpExcel column size issues

Tags:

php

phpexcel

I want to make sure that no value is cut off in a workbook produced by phpExcel. To do this I call

  $oCurrentSheet->getColumnDimension($aCurrentCoords['x'])->setAutoSize(true);

every time I write a cell. This doesn't seem to work: Many columns end up really tiny.

Does anybody know how to make sure every column in the outputted excel workbook is sized according to its content?

like image 572
Sheena Avatar asked Apr 01 '12 15:04

Sheena


1 Answers

Don't do this every time you write a cell... it's an unnecessary overhead. Do it just once for each column.

Be warned, it's still expensive when saving, because PHPExcel then walks through each cell in that column working out the width necessary based on the content of that cell, taking into account formula calculation and formatting, and using the maximum size of any cell in that column. Even then it isn't a perfect solution: the default behaviour is to estimate, counting the number of characters to display, and using a generic multiplier based on font (Arial, Verdana of Calibri) and a little bit of padding. For a more accurate calculation, you can change the method used for the calculation, and the code then uses GD to build a ttf bounding box and base the cell size on the dimensions of that box. This is a more accurate calculation, but a lot slower.

You can change the calculation method using:

PHPExcel_Shared_Font::setAutoSizeMethod($method);

before saving, where $method is one of the following:

PHPExcel_Shared_Font::AUTOSIZE_METHOD_APPROX
PHPExcel_Shared_Font::AUTOSIZE_METHOD_EXACT

This still isn't a perfect solution, but it's the best calculation that PHPExcel can do.

An alternative is to call the worksheet's calculateColumnWidths() method yourself directly before saving... and then walk through each column's dimension increasing the value by perhaps 5% to try and ensure that the entire column fits, before saving.

like image 57
Mark Baker Avatar answered Nov 08 '22 00:11

Mark Baker