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 a column is set to AutoSize, PHPExcel attempts to calculate the column width based on the calculated value of the column (so on the result of any formulae), and any additional characters added by format masks such as thousand separators.
By default, this is an
estimated
width: a more accurate calculation method is available, based on using GD, which can also handle font style features such as bold and italic; but this is a much bigger overhead, so it is turned off by default. You can enable the more accurate calculation usingHowever, autosize doesn't apply to all Writer formats... for example CSV. You don't mention what writer you're using.
But you also need to identify the columns to set dimensions:
$objPHPExcel->getActiveSheet()->getColumnDimension()
expects a column ID.$objPHPExcel->getActiveSheet()->getColumnDimensions()
will return an array of all the defined column dimension records; but unless a column dimension record has been explicitly created (perhaps by loading a template, or by manually callinggetColumnDimension()
) then it won't exist (memory saving).Here a more flexible variant based on @Mark Baker post:
Hope this helps ;)
This is example how to use all columns from worksheet:
you also need to identify the columns to set dimensions:
This code snippet will auto size all the columns that contain data in all the sheets. There is no need to use the activeSheet getter and setter.
If you need to do that on multiple sheets, and multiple columns in each sheet, here is how you can iterate through all of them: