Search code examples
phpwidthphpexcelautosize

How to PHPExcel set auto-columns width


I'm working with PHPExcel to export data for download. When open downloaded files, with cells have big number, it show "#######" instead of value number. I'm tried setAutoSize() for every columns then call $sheet->calculateColumnWidths() but it still not changes. I see calculateColumnWidths() at here, @Mark Baker says "calculateColumnWidths() increase the value by perhaps 5% to try and ensure that the entire column fits". If number length in cell exceed 5%, it seems doen's resolved the problem

UPDATE This is my function to auto size columns:

   function autoFitColumnWidthToContent($sheet, $fromCol, $toCol) {
        if (empty($toCol) ) {//not defined the last column, set it the max one
            $toCol = $sheet->getColumnDimension($sheet->getHighestColumn())->getColumnIndex();
        }
        for($i = $fromCol; $i <= $toCol; $i++) {
            $sheet->getColumnDimension($i)->setAutoSize(true);
        }
        $sheet->calculateColumnWidths();
    }

Solution

  • First potential problem may be that you're working with column letters. PHP's incrementor operation will work with column letters, so if $i is 'A', then $i++ will give 'B', and if $i is 'Z' than $i++ will give 'AA'; but you can't use <= as your comparator, as 'AA' is <= 'Z' when executed as a straight comparison.

    Instead of

    for($i = $fromCol; $i <= $toCol; $i++) {
    

    use

    $toCol++;
    for($i = $fromCol; $i !== $toCol; $i++) {
    

    To add the 5% margin after calling $sheet->calculateColumnWidths() do:

    for($i = $fromCol; $i !== $toCol; $i++) {
        $calculatedWidth = $sheet->getColumnDimension($i)->getWidth();
        $sheet->getColumnDimension($i)->setWidth((int) $calculatedWidth * 1.05);
    }