I'm trying to auto size the columns of my sheet. I'm writing the file and in the end I try to resize all of my columns.
// Add some data
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('B1', 'test1111111111111111111111')
->setCellValue('C1', 'test1111111111111')
->setCellValue('D1', 'test1111111')
->setCellValue('E1', 'test11111')
->setCellValue('F1', 'test1')
->setCellValue('G1', 'test1');
foreach($objPHPExcel->getActiveSheet()->getColumnDimension() as $col) {
$col->setAutoSize(true);
}
$objPHPExcel->getActiveSheet()->calculateColumnWidths();
The above code doesn't work. Doesn't change the column size to fit the text
UPDATE
The writer I'm using $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
If you try to iterate with
for ($col = 2; $col <= 'AC'; ++ $col){...}
, or withforeach(range('A','AC') as $col) {...}
it will work for columns from A to Z, but it fails pass the Z (Ex. iterate between 'A' to 'AC').In order to iterate pass 'Z', you need to convert the column to integer, increment, compare, and get it as string again:
With this, you easy iterate pass the 'Z' column and set autosize to every column.
In case somebody was looking for this.
The resolution below also works on
PHPSpreadsheet
, their new version of PHPExcel.What these methods do:
getHighestColumn($row = null)
- Get highest worksheet column.getHighestDataColumn($row = null)
- Get highest worksheet column that contains data.getHighestRow($column = null)
- Get highest worksheet rowgetHighestDataRow($column = null)
- Get highest worksheet row that contains data.Come late, but after searching everywhere, I've created a solution that seems to be "the one".
Being known that there is a column iterator on last API versions, but not knowing how to atuoadjust the column object it self, basically I've created a loop to go from real first used column to real last used one.
Here it goes:
For Spreedsheet + PHP 7, you must write instead of
PHPExcel_Cell::columnIndexFromString
,\PhpOffice\PhpSpreadsheet\Cell::columnIndexFromString
. And at the loop is a mistake, there you must<
not work with<=
. Otherwise, he takes a column too much into the loop.