如何更改字符laravel excel maatwebsite的颜色?

时间:2018-08-06 08:49:32

标签: excel laravel laravel-5 laravel-5.6 laravel-excel

我从这里获得教程:https://laravel-excel.maatwebsite.nl/3.0/exports/extending.html

所以我使用版本3

我的excel这样:

enter image description here

我想将其更改为这样:

enter image description here

所以我希望字符England变为红色和粗体

我这样尝试:

namespace App\Exports;
...
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Events\BeforeExport;
use Maatwebsite\Excel\Events\AfterSheet;

class SummaryExport implements FromView, WithEvents
{
    ...
    public function registerEvents(): array
    {
        return [
            AfterSheet::class    => function(AfterSheet $event) {
                $event->sheet->styleCells(
                    'B1:D1',
                    [
                        'borders' => [
                            'outline' => [
                                'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THICK,
                                'color' => ['argb' => 'EB2B02'],
                            ],
                        ]
                    ]
                );
            },
        ];
    }
}

存在这样的错误:

Method Maatwebsite\Excel\Sheet::styleCells does not exist.

如何解决此错误?

1 个答案:

答案 0 :(得分:1)

您可以在服务提供商的boot方法中注册宏。例如,App\Providers\AppServiceProvider提供者的外观如下:     

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use \Maatwebsite\Excel\Sheet;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
        Sheet::macro('styleCells', function (Sheet $sheet, string $cellRange, array $style) {
            $sheet->getDelegate()->getStyle($cellRange)->applyFromArray($style);
        });
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}
  

您应该创建其他服务提供商来抵抗这种宏,以隔离第三方的顾虑。

对于字体颜色设置字体样式:

public function registerEvents(): array
{
    return [
        AfterSheet::class    => function(AfterSheet $event) {
            $event->sheet->styleCells(
                'B1:D1',
                [
                    'borders' => [
                        'outline' => [
                            'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THICK,
                            'color' => ['argb' => 'EB2B02'],
                        ],

                    ],
                    'font' => array(
                        'name'      =>  'Calibri',
                        'size'      =>  15,
                        'bold'      =>  true,
                        'color' => ['argb' => 'EB2B02'],
                    )
                ]
            );
        },
    ];
}