Laravel Excel 垂直居中对齐

Laravel Excel vertical align center

如何使中心单元格与 laravel Excel 垂直对齐?

我的代码:

$sheet->cells('A1:'.$column_end.$i, function ($cells) {
                $cells->setBackground('#d8d8d8');
                $cells->setFontWeight('bold');
                $cells->setValignment('middle');
            });

但这不起作用,我的大部分单元格都是垂直对齐底部的。

可能不是中间!

我试过 'center' 但也没用。当我尝试 'top' 或 'bottom' 时,它起作用了。

那么为什么 'middle' 或 'center' 没有?

感谢您的帮助。

根据Laravel Excel Documentation,应该是:

$cells->setValignment('center');

就像你提到的...

尝试作为测试,setAlignment('center'),根据它,行为应该是相同的,但对于水平。如果这个有效,那么另一个应该是肯定的。

试试这个

$sheet->cell('A1:G1',function($cell){ $cell->setAlignment('center'); $cell->setFontWeight('bold'); });

我遇到了同样的问题,我不得不深入了解它是如何工作的并弄明白了,所以我想在这里发表评论以防其他人偶然发现这个话题

Laravel Excel uses phpspreadsheet 并提供了一个简单的 Larave 接口和逻辑来使用它,但没有太多解释,所以,首先是工作代码(进入 Exports\MyExportClassExport.php):

/**
     * @return array
     */
    public function registerEvents(): array
    {
        return [
            AfterSheet::class    => function(AfterSheet $event) {
                $event->sheet->getDelegate()->getStyle('A2:W2')->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
            },
        ];
    }

但是它是如何工作的,为什么?

为了完全控制 spreadsheet 和 Phpspreadsheet 的所有真正有用的组件,Laravel-excel 让您可以与创建所有内容后触发的一系列 events, so we are using the AfterSheet 事件进行交互。我不是 phpspreadsheet 方面的专家,也不是 Laravel Excel 方面的专家,所以也许有人可以为我正在做的事情建议一个更好的活动,无论如何它有效。

我们现在可以通过带有 $event 变量的闭包访问 AfterSheet,我们可以访问两个不同的属性:sheet 和可导出(请参阅来自 Phpspread 的 AfterSheet class) and we get from the sheet property (which is the Sheet object) the delegate with getDelegate() method and here is the important part. We are now working with the Worksheet class sheet!

所以从现在开始,我们只需要遵循documentation for Phpspreadsheet,我们就可以随心所欲地编写代码了!

我希望这对像我一样在没有真正答案的情况下遇到这个话题的人有所帮助,或者至少会有所帮助。