Center all text in PHPSpreadsheet and make the cells expand to fill up with context Center all text in PHPSpreadsheet and make the cells expand to fill up with context php php

Center all text in PHPSpreadsheet and make the cells expand to fill up with context


This would do the trick:

For autosizing (cell automatic expansion) do this:

$sheet->getColumnDimension('A')->setAutoSize(true);$sheet->getColumnDimension('B')->setAutoSize(true);

NOTE

You have to do this individually for each column as the getColumnDimension method can only accept one column as it's parameter.

You have already figured out the horizontal alignment, but it is worth noting that you can set the alignment of more than one column using one command.

$sheet->getStyle('A:B')->getAlignment()->setHorizontal('center');

As for setting the cells values, I would prefer you do it separately from anything that has to do with formatting and styling just for the purpose of separation of concerns and readability.

Cheers.


For autosizing a range of columns:

foreach(range('A','Z') as $columnID) {    $sheet->getColumnDimension($columnID)->setAutoSize(true);}

Set the info in every cell to be centered:

$alignment_center = \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER;foreach($sheet->getRowIterator() as $row) {    foreach($row->getCellIterator() as $cell) {        $cellCoordinate = $cell->getCoordinate();        $sheet->getStyle($cellCoordinate)->getAlignment()->setHorizontal($alignment_center);    }}

These work for:

"phpoffice/phpspreadsheet": "^1.6"


  1. Set the info in every cell to be centered since it makes better for printing to PDF/etc.

As $sheet->getStyle('A:B') didn't work with me so here is an alternative.

 $lastColumn = $sheet->getHighestColumn(); $lastRow = $sheet->getHighestRow(); $sheet->getStyle("A1:$lastColumn$lastRow")->applyFromArray($styleArray); // "A1:$lastColumn$lastRow" this is basically means apply style from the first cell to last cell (last column)
  1. Make the cells expand based on how much text there is in the cell. I dont want the the information in A to go over in cell B.
$sheet->getColumnDimension('B')->setAutoSize(true);

you can also loop on columns and apply autosize to every column.