Tuesday, October 4, 2022

[FIXED] How to middle align cell value in PhpSpreadsheet?

Issue

I want to align the cell value to the middle. My output looks like this:-

Current output

My expected output should be this:

Desired output

I want every column to be in the center. I tried the following code:

$styleArray = [
    'font' => [
        'bold' => true,
    ],
    'alignment' => [
        'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
    ],
    'fill' => [
        'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID,
        'startColor' => [
            'argb' => '0070C0',
        ],
        'endColor' => [
            'argb' => '0070C0',
        ],
    ],
];

$spreadsheet->getDefaultStyle()->getFont()->setSize(10);

I tried all the other attributes like HORIZONTAL_CENTER, RIGHT, LEFT, JUSTIFY, etc. How can I do this properly?


Solution

You're setting the wrong (and one too few) key(s) for the alignment setting. What you're attempting to achieve is the vertical and horizontal alignment of the text.

'alignment' => [
    'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
    'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
],

PhpSpreadsheet docs



Answered By - esqew
Answer Checked By - Timothy Miller (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.