3

I try to style my spreadsheet with the PHPSpreadsheet calls. I want to center the text vertical and horizontal. What I do is this:

$spreadsheet = new Spreadsheet();
$spreadsheet->setActiveSheetIndex(0)->setCellValue('A1', 'Name');
$spreadsheet->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
...
...
...
foreach (range('A', 'E') as $columnID) {
    $spreadsheet->getActiveSheet()->getColumnDimension($columnID)->setAutoSize(true);
    $spreadsheet->getActiveSheet()->getStyle($columnID)->getAlignment()->setHorizontal('center');
    $spreadsheet->getActiveSheet()->getStyle($columnID)->getAlignment()->setVertical('center');
}

But when I open the excel file, the text is not centered. What I am doing wrong?

1 Answers1

3

Ok the problem is, it is not working with range. You need to do this:

$spreadsheet->getActiveSheet()->getStyle('D1')->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT);
$spreadsheet->getActiveSheet()->getStyle('D1')->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_TOP);

You have to add the cell number

  • 1
    It may be down to the format of the column you try to use https://stackoverflow.com/a/13307949/1213708 suggests the range should be something like `->getStyle('E1:E256')`. – Nigel Ren May 28 '20 at 06:16