Center Text vertical and horizontal in PHPSpreadsheet

Viewed 2248

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 Answers

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

Related