laravelphpspreadsheetlaravel-excel

How to add password to Excel file in Laravel


I am learning Laravel Framework. I like to know if there is a package or tool that automatically adds or insert password into Excel file in Laravel application so that registered user can open the file with password known to the user only after downloading it.


Solution

  • You can add maatwebsite/excel package for Laravel which is a wrapper around phpoffice/phpspreadsheet package.

    Here is the docs on how to set security on a spreadsheet on PhpSpreadsheet: https://phpspreadsheet.readthedocs.io/en/latest/topics/recipes/#setting-security-on-a-spreadsheet

    See extending section of the laravel-excel documentations to learn how to call PhpSpreadsheet methods on a event or using a macro.

    The final code would be something like this:

    namespace App\Exports;
    
    use Maatwebsite\Excel\Concerns\WithEvents;
    use Maatwebsite\Excel\Events\BeforeExport;
    
    class InvoicesExport implements WithEvents
    {
        /**
         * @return array
         */
        public function registerEvents(): array
        {
            return [
                BeforeExport::class  => function(BeforeExport $event) {
                    $event->writer->getDelegate()->getSecurity()->setLockWindows(true);
                    $event->writer->getDelegate()->getSecurity()->setLockStructure(true);
                    $event->writer->getDelegate()->getSecurity()->setWorkbookPassword("Your password");
                }
            ];
        }
    }