PHPExcel: How to Set the Width of Cells CodeUnit 12 JUL 2010

PHPExcel is a phenomenal Excel generating library for PHP which I have mentioned on this site numerous times before, and which is currently my defacto way for quickly knocking out all those annoying Excel downloads that clients always seem to MUST have! ;)

Today’s quick code tip is on how to specify or set the width of individual columns in your worksheet.

In order to do this, we make use of the handy setWidth function that allows us to specify the width of our targeted column using the standard Excel column width units.

So let’s see this in code then:

$workbook = new PHPExcel;
$sheet = $workbook->getActiveSheet();
$writer = new PHPExcel_Writer_Excel5($workbook);
header('Content-type: application/');

And there you go, as simple as that!

Related Link:

Related Posts:

About Craig Lotter

South African software architect and developer at Touchwork. Husband to a cupcake baker and father to two little girls. I don't have time for myself any more.

  • Juan Carlos Horna

    Buen generador de archivos excel… recomendado

  • Longinustorwaldzki

    Thanks Man,

    good to have people like U in the Internet.


  • Appu

    Hi Craig

       I tried above example to set the cell width dynamically, it’s not working.  please suggest me how to set cell width dynamically with string value.


     $val = “Welcome to PHPExcel” ;


      Please give me the response ASAP.


    • I’m not sure, but your function linking looks suspect in the first place. getColumnDimensionByColumn doesn’t look like it will produce a column which you can then chain the setWidth onto. Also, strlen returns the number of characters of the string. Isn’t really the unit used to set the column width is it?