-
I have a spreadsheet where I want to auto-size all the columns I have populated, as well as the first cell in each column (bold for headings). At the moment I am using the built-in PHP foreach(range('A', 'Z') as $column) {
$worksheet->getCell("{$column}1")->getStyle()->getFont()->setBold(true);
$worksheet->getColumnDimension($column)->setAutoSize(true);
} That works fine when the range covers single-character cells, but I'm currently using PhpSpreadsheet 1.8.2 (I know this is out of date but the underlying PHP version is 5.6 and I can't change that without upgrading the whole server). |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
I eventually solved this via the use of $highest_column_index = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($worksheet->getHighestColumn(1));
foreach (range(1, $highest_column_index) as $column) {
$worksheet->getCellByColumnAndRow($column, 1)->getStyle()->getFont()->setBold(true);
$worksheet->getColumnDimensionByColumn($column)->setAutoSize(true);
} |
Beta Was this translation helpful? Give feedback.
-
You can write your own variant of I'm just using it as a closure here; but if it's something that you use frequently in your code then it can be written as a standalone function. $columnRange = function($startColumn, $endColumn) {
++$endColumn;
for($column = $startColumn; $column !== $endColumn; ++$column) {
yield $column;
}
};
foreach($columnRange('A', 'AB') as $column) {
echo $column, PHP_EOL;
} |
Beta Was this translation helpful? Give feedback.
I eventually solved this via the use of
columnIndexFromString
andgetHighestColumn
: