Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to middle align cell value in PhpSpreadsheet?

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?

like image 521
kunal Avatar asked Mar 13 '19 11:03

kunal


Video Answer


1 Answers

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

like image 69
esqew Avatar answered Sep 17 '22 19:09

esqew