phpspreadsheet支持单元格水平、垂直对齐的灵活设置,可应用于单个单元格、区域或整表,默认样式影响新写入单元格,配合wraptext与行高可实现多行文本居中显示。

PhpSpreadsheet 提供了灵活的单元格对齐控制,支持水平、垂直方向单独或组合设置,还能应用到单个单元格、区域甚至整张表。
设置单个或多个单元格的对齐方式
用 getStyle() 获取样式对象,再通过 getAlignment() 配置对齐参数:
- 水平居中 + 垂直居中:
$sheet->getStyle('A1')->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER)->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER); - 左对齐 + 垂直居中:
$sheet->getStyle('B2:C5')->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_LEFT)->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER); - 右对齐 + 顶部对齐:
$sheet->getStyle('D1')->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT)->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_TOP);
设置整张工作表的默认对齐方式
对所有新写入的单元格生效,适合统一排版:
- 全局水平居中:
$spreadsheet->getDefaultStyle()->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER); - 全局垂直居中:
$spreadsheet->getDefaultStyle()->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER); - 同时设为水平+垂直居中(两行都要写):
$spreadsheet->getDefaultStyle()->getAlignment()->setHorizontal(...);<br> $spreadsheet->getDefaultStyle()->getAlignment()->setVertical(...);
配合自动换行与居中显示
常用于多行文本内容,避免文字被截断:
$sheet->getStyle('A4:J8')->getAlignment()->setWrapText(true)->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER)->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);- 注意:自动换行需配合足够高的行高,否则可能看不见全部内容;可同步设置:
$sheet->getRowDimension('4')->setRowHeight(40);
常用对齐常量速查
水平方向:HORIZONTAL_LEFT、HORIZONTAL_CENTER、HORIZONTAL_RIGHT、HORIZONTAL_JUSTIFY、HORIZONTAL_FILL
垂直方向:VERTICAL_TOP、VERTICAL_CENTER、VERTICAL_BOTTOM、VERTICAL_JUSTIFY
php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!











