PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, October 5, 2022

[FIXED] How to PHPExcel set auto-columns width

 October 05, 2022     autosize, php, phpexcel, width     No comments   

Issue

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);
}


Answered By - Mark Baker
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing