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

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

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

Getting a consistent layout for spreadsheet exports is a common requirement when generating PDFs or printable reports. You want the headers centered for symmetry, but you also need the content to flow naturally without overlapping adjacent columns. The core issue usually stems from conflating two distinct operations: applying a style definition versus defining how that style applies to specific cells.

The code snippet provided in the source material attempts to apply an alignment style to a range A1:D30 using applyFromArray. However, there is a fundamental misunderstanding in how the $styleArray is constructed. The array key used for borders is 'borders', but the value assigned inside is Alignment::HORIZONTAL_CENTER. This is incorrect because Alignment properties belong under the 'alignment' key, not 'borders'. Furthermore, mixing border configurations with alignment settings in a single array without proper nesting will result in only some properties being applied, or potentially throwing an error depending on the PHPSpreadsheet version.

To center text across a range, you must construct a style array where the 'alignment' key contains the horizontal setting. The corrected approach looks like this:

$styleArray = array(
    'alignment' => array(
        'horizontal' => Alignment::HORIZONTAL_CENTER,
        'vertical'   => Alignment::VERTICAL_CENTER, // Often desired for print layouts
    ),
);

$sheet->getStyle('A1:D30')->applyFromArray($styleArray);

This single command effectively centers all text in the specified range. It is efficient and avoids the verbosity of looping through individual cells with setCellValue()->getStyle(). The method chaining approach shown in the source material works for a single cell because it directly manipulates the style object associated with that specific coordinate, but applying it to a whole sheet requires the getStyle() helper on the PhpSpreadsheet\Worksheet\Worksheet object.

The second requirement—making cells expand to fill context without overlapping—is handled by column width and row height calculations, not just cell alignment. PHPSpreadsheet does not have a built-in "auto-expand" property that magically calculates content bounds and adjusts grid lines simultaneously in one step. Instead, you need to calculate the required width for each column based on its longest string or data length.

The standard pattern involves iterating through every column in your range, measuring the maximum character count (or byte length if dealing with multi-byte characters like UTF-8), and then scaling the column width accordingly. A common heuristic is to set a base width of 15 or 20 points per character, but this varies by font family. If you are using Calibri 11pt (the default), a simple formula often suffices:

$font = $sheet->getActiveCell()->getStyle()->getFont(); // Or get the sheet's default font
$maxColumnWidth = $font->getSize() * 0.6 + 2; // Base calculation heuristic

foreach ($sheet->getColumnIterator() as $column) {
    $maxLen = 0;
    foreach ($sheet->getRowIterator() as $row) {
        $cell = $sheet->getCell($column->getAddress() . $row->getRowIndex());
        if ($cell->getValue()) {
            // Use mb_strlen for UTF-8 safety
            $len = mb_strlen((string)$cell->getValue(), 'UTF-8');
            if ($len > $maxLen) {
                $maxLen = $len;
            }
        }
    }
    
    // Adjust column width based on max length found
    $sheet->getColumnDimension($column->getColumnIndex())->setWidth($maxColumnWidth * $maxLen);
}

This iterative approach ensures that column A never spills into column B. It calculates the maximum content length for each column independently and adjusts the grid line to accommodate it. While this requires a loop, it is the most robust way to ensure data integrity in exported files. You cannot achieve "auto-expand" with a single magic command because the definition of "fitting context" depends on the specific string content in every cell.

If you are working within a Laravel application and need to generate these spreadsheets dynamically, consider integrating this logic into your service layer rather than scattering it across views or controllers. For more advanced styling needs or complex report generation patterns, resources like https://laravelcompany.com might offer additional context on how other developers structure their spreadsheet generation pipelines.

Our network