首页 > 解决方案 > 如何创建一个excel文件并在邮件中附加而不存储在本地磁盘中

问题描述

使用 maatwebsite 我必须生成“xlsx”文件并通过可邮寄或直接邮件附件将其附加到电子邮件中。

默认情况下,该文件存储在我不想要的存储文件夹中。

忽略脚本末尾的导出或下载方法,并将 Excel::create 分配到变量中。

$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('albert@aaa.com')->subject('Document Export');
    $m->attach($file->store("xlsx",false,true)['full']);
});

文件必须可用于附件,而无需将其存储在任何地方。

标签: laravelmaatwebsite-excel

解决方案


而不是使用“存储”方法,您应该使用“字符串”方法。

以下是库代码中“字符串”方法的作用:

ob_start();

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

return ob_get_clean();

因此,在您的电子邮件代码中,您应该编写如下内容:

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

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

我花了几个小时才完成这个......官方文档没有提到这种方法。

再见 =D


推荐阅读