如何在 PhpSpreadsheet 中对齐单元格值?

How to middle align cell value in PhpSpreadsheet?

我想将单元格值居中对齐。我的输出如下所示:-

我的预期输出应该是这样的:

我希望每一列都在中间。我尝试了以下代码:

$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);

我尝试了所有其他属性,例如 HORIZONTAL_CENTERRIGHTLEFTJUSTIFY 等。我该如何正确执行此操作?

您为 alignment 设置设置了错误(而且太少)的键。您要实现的是 vertical and horizo​​ntal 对齐文本。

'alignment' => [
    'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
    'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
],

PhpSpreadsheet docs

除了你还可以用方法链接的方式来做:

$spreadsheet->getActiveSheet()->getStyle($cells)->getAlignment()->setHorizontal($align)

$spreadsheet->getActiveSheet()->getStyle($cells)->getAlignment()->setVertical($align);
  • $cells 应该是单个单元格 ('A1') 或一系列单元格 ('A1:E4')。
  • $align 应该是所需对齐方式的 \PhpOffice\PhpSpreadsheet\Style\Alignment class(或其字符串值)的常量。
    • 对于水平对齐:
      • Alignment::HORIZONTAL_GENERAL'general'
      • Alignment::HORIZONTAL_LEFT'left'
      • Alignment::HORIZONTAL_RIGHT'right'
      • Alignment::HORIZONTAL_CENTER'center'
      • Alignment::HORIZONTAL_CENTER_CONTINUOUS'centerContinuous'
      • Alignment::HORIZONTAL_JUSTIFY'justify'
      • Alignment::HORIZONTAL_FILL'fill'
      • Alignment::HORIZONTAL_DISTRIBUTED'distributed'(仅限 Excel2007)
    • 对于垂直对齐:
      • Alignment::VERTICAL_BOTTOM'bottom'
      • Alignment::VERTICAL_TOP'top'
      • Alignment::VERTICAL_CENTER'center'
      • Alignment::VERTICAL_JUSTIFY'justify'
      • Alignment::VERTICAL_DISTRIBUTED'distributed'(仅限 Excel2007)

这些的来源是source