简体   繁体   中英

Center Text vertical and horizontal in PHPSpreadsheet

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM