Albert
Albert

Reputation: 174

How to create an excel file and attach in mail without store in local disk

Using maatwebsite I have to generate the 'xlsx' file and attach the same in the email through mailable or direct mail attachment.

By default the file is stored in storage folder which I don't want.

Ignored the export or download method at the end of the script and assigned that Excel::create in a variable.

$file = Excel::create($fileName, function($excel) use($valuesInArray) {
    $excel->sheet('Sheetname', function($sheet) use($valuesInArray) {
        $sheet->fromArray($valuesInArray);
    });
});

Mail::send('email.documents_export',["user"=>"Albert", "clientName" => "AAA"],function($m) use($file){
    $m->to('[email protected]')->subject('Document Export');
    $m->attach($file->store("xlsx",false,true)['full']);
});

File has to be available for attachment without store it anywhere.

Upvotes: 3

Views: 3608

Answers (1)

Riccardo Galeazzi
Riccardo Galeazzi

Reputation: 31

Instead of using the "store" method you should use the "string" one.

Here is what the "string" method does from the library code:

ob_start();

$this->writer->save('php://output');

return ob_get_clean();

So in your email code you should write something like this:

$file = Excel::create($fileName, function($excel){
   // Your code here
});

Mail::send('email.documents_export',["user"=>"Albert", "clientName" => AAAA"],function($m) use($file){
    $m->to('[email protected]')->subject('Document Export');
    $m->attachData($file->string("xlsx"), $fileName);
});

It took me a couple hours to get through this... The official doc didn't mention this method.

Bye =D

Upvotes: 3

Related Questions