Setting width of spreadsheet cell using PHPExcel
PhpPhpexcelPhpspreadsheetPhp Problem Overview
I'm trying to set the width of a cell in an Excel document generated with PHPExcel with:
$objPHPExcel->getActiveSheet()->getColumnDimensionByColumn('C')->setWidth('10');
$objPHPExcel->getActiveSheet()->getColumnDimensionByColumn('C')->setAutoSize(false);
but that does not works.
What is the method that I need to call here?
Php Solutions
Solution 1 - Php
It's a subtle difference, but this works fine for me:
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(10);
Notice, the difference between getColumnDimensionByColumn
and getColumnDimension
Also, I'm not even setting AutoSize and it works fine.
Solution 2 - Php
setAutoSize method must come before setWidth:
$objPHPExcel->getActiveSheet()->getColumnDimensionByColumn('C')->setAutoSize(false);
$objPHPExcel->getActiveSheet()->getColumnDimensionByColumn('C')->setWidth('10');
Solution 3 - Php
hi i got the same problem.. add 0.71 to excel cell width value and give that value to the
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(10);
eg: A Column width = 3.71 (excel value)
give column width = 4.42
will give the output file with same cell width.
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(4.42);
hope this help
Solution 4 - Php
Tha is because getColumnDimensionByColumn receives the column index (an integer starting from 0), not a string.
The same goes for setCellValueByColumnAndRow
Solution 5 - Php
autoSize for column width set as bellow. It works for me.
$spreadsheet->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
Solution 6 - Php
This worked for me:
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(false);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(10);
be sure to add setAuzoSize(false)
, before the setWidth();
as Rolland mentioned
Solution 7 - Php
The correct way to set the column width is by using the line as posted by Jahmic, however it is important to note that additionally, you have to apply styling after adding the data, and not before, otherwise on some configurations, the column width is not applied
Solution 8 - Php
This way is much easier to adjust the size of the columns automatically.
foreach (range('A', 'I') as $letra) {
$spreadsheet->getActiveSheet()->getColumnDimension($letra)->setAutoSize(true);
}