返回内存的数据

public function getExcel($expiredTime, $city)
    {
        ob_start();
        $expiredTime = $expiredTime > 0 ? $expiredTime : time();
        $sevenDate   = date('Y-m-d H:i:s', $expiredTime - 604800);
        DB::connection()->enableQueryLog();

        $sql  = $this->getSql($city['city'], $expiredTime, $sevenDate);
        $data = DB::select($sql);

        $spreadsheet = new Spreadsheet();
        $sheet       = $spreadsheet->getActiveSheet();

        //设置sheet的名字  两种方法
        $sheet->setTitle('店铺基础数据');

        //设置第一行小标题
        $k = 1;
        $sheet->setCellValue('A' . $k, '类型');
        $sheet->setCellValue('B' . $k, '运营人员');
        $sheet->setCellValue('C' . $k, '邀请人');
        $sheet->setCellValue('D' . $k, '客户名称');

        $k = 2;
        foreach ($data as $datum) {
            $sheet->setCellValue('A' . $k, $datum->user_type);
            $sheet->setCellValue('B' . $k, (string)$datum->运营人员);
            $sheet->setCellValue('C' . $k, (string)$datum->邀请人);
            $sheet->setCellValue('D' . $k, (string)$datum->客户名称);

            $k++;
        }

        $writer = IOFactory::createWriter($spreadsheet, 'Xls');
        //注意createWriter($spreadsheet, 'Xls') 第二个参数首字母必须大写
        $writer->save('php://output');

        $out = ob_get_contents();
        ob_clean();

        return $out;
    }
$to = ['791315894@qq.com', 'hxslcc@gmail.com'];
Mail::send(new UserCarInfoReport($to, "用户统计周报", $fileData, compact('date', 'fileName')));

将内存中的数据根据attachData方法添加到附近

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

class UserCarInfoReport extends Mailable
{
    use Queueable, SerializesModels;

    // mailable 类中定义的任何公共属性将自动传递给视图
    private $fileData;

    /**
     * Create a new message instance.
     *
     * @param $to 收件人
     * @param $subject 主题
     * @param $fileData 内存文件数据
     * @param $viewData 显示的数据
     */
    public function __construct($to, $subject, $fileData, $viewData)
    {
        $this->setAddress($to); // 根据数组设置 $this->to;

        $this->subject  = $subject;
        $this->fileData = $fileData;
        $this->viewData = $viewData;
        $this->view     = 'emails.user_car_info_report';
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->attachData(
            $this->fileData,
            $this->viewData['fileName'],
            [
                'mime' => 'application/vnd.ms-excel'
            ]
        );
    }
}