How to add sub or super script in a cell to export with Laravel Excel

 The situation I was in required me to add subscript to a value. It was a static value (heading) so this made things much simpler.

Step 1:

Make sure you register events on your sheet

I missed this for a while and was wondering why none of my events worked.

... implements WithEvents

Step 2:

Next, if you don't already have a register events method, add that in

    public function registerEvents(): array

    {

        return [];

    }

In the return statement is where the logic will go for after sheet events

Step 3:

Add an after sheet function to the registered events array, you can use multiple event registration methods but I will show the way using a closure

        return [

            AfterSheet::class => function (AfterSheet $event) {

                $delegate = $event->sheet->getDelegate();

        }];

Step 4:

Fill your logic in below the delegate declaration

I am going to use a very basic example without pulling information from anywhere


        $subscriptValue = new RichText();

        $subscriptValue->createText('H');

        $subscript = $subscriptValue->createTextRun('2');

        $subscript->getFont()->setSubscript(true);

        $lastText = $subscriptValue->createTextRun('O');

        $delegate->getCell('A1')->setValue($subscriptValue);


Thats it! you should now have a cell, A1 set with a subscript number in the middle

Comments