Reputation: 43
I've used previous versions of Laravel-Excel to export data and in the past I've been able to use $sheets->setActiveSheetIndex(0)->download('xls');
(link to PHPSpreadsheet documentation) to set the active tab when the user opens the file.
In version 3.0, I can't figure out where to put this. The file downloads if I don't try to set the active sheet so the rest of the code is valid. I've tried adding it inside the export controller as shown below and it throws an error Call to undefined method App\Exports\TechMatrixExport::setActiveSheetIndex()
. In the example below I want TechnologiesSheet to be the active when when the user opens the file.
namespace App\Exports;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\WithMultipleSheets;
class TechMatrixExport implements WithMultipleSheets
{
use Exportable;
public function sheets(): array
{
$sheets = [];
$sheets[] = new TechnologiesSheet();
$sheets[] = new NotesSheet();
$sheets[] = new InputsSheet();
$sheets[] = new ReferencesSheet();
return $sheets;
}
}
Controller:
public function __construct(\Maatwebsite\Excel\Excel $excel)
{
$this->excel = $excel;
}
public function exportAll()
{
return (new TechMatrixExport)->setActiveSheetIndex(0)->download('tech_matrix.xlsx');
}
Where does the ->setActiveSheetIndex(0);
belong?
Upvotes: 4
Views: 3763
Reputation: 36
You should use BeforeWriting (https://laravel-excel.maatwebsite.nl/3.0/exports/extending.html#available-events) to setActiveSheetIndex.
I added RegistersEventListeners to your code, I got it working this way in my project, let me know if this works for you.
namespace App\Exports;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\WithMultipleSheets;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Concerns\RegistersEventListeners;
use Maatwebsite\Excel\Events\BeforeExport;
use Maatwebsite\Excel\Events\BeforeWriting;
class TechMatrixExport implements WithMultipleSheets, WithEvents
{
use Exportable, RegistersEventListeners;
public function registerEvents(): array
{
return [
// Handle by a closure.
BeforeExport::class => function(BeforeExport $event) {
$event->writer->getProperties()->setCreator('You')->setTitle("Title");
},
BeforeWriting::class => function(BeforeWriting $event) {
$event->writer->setActiveSheetIndex(0);
},
];
}
public function sheets(): array
{
$sheets = [];
$sheets[] = new TechnologiesSheet();
$sheets[] = new NotesSheet();
$sheets[] = new InputsSheet();
$sheets[] = new ReferencesSheet();
return $sheets;
}
}
Upvotes: 2