You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Laravel8中使用Maatwebsite3实现无Model的Excel导出功能

Laravel8 + Maatwebsite 3.x 无Model实现Excel导出方案

Maatwebsite本身没有强制要求必须绑定Model,直接通过自定义数据注入即可实现需求,以下是三部分完整代码:

1. 完善ExportExcel类

<?php

namespace App\Exports;

use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;

class ExportExcel implements FromCollection, WithHeadings
{
    protected $exportData;
    protected $headings;

    // 构造方法接收外部传入的任意自定义数据,无需关联Model
    public function __construct(array $exportData, array $headings = [])
    {
        $this->exportData = $exportData;
        $this->headings = $headings;
    }

    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        return new Collection($this->exportData);
    }

    // 返回Excel表头,不需要表头可以删除WithHeadings接口和这个方法
    public function headings(): array
    {
        return $this->headings;
    }
}

2. 控制器与路由配置

控制器代码

<?php

namespace App\Http\Controllers;

use App\Exports\ExportExcel;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Http\Request;

class ExportController extends Controller
{
    public function export(Request $request)
    {
        // 此处可自定义组装任意数据,支持手动拼接、查询构造器原生查询、第三方接口返回数据等多种来源
        // 示例:手动组装二维数组
        $exportData = [
            ['id' => 1, 'name' => '张三', 'mobile' => '13800000001'],
            ['id' => 2, 'name' => '李四', 'mobile' => '13800000002'],
            ['id' => 3, 'name' => '王五', 'mobile' => '13800000003'],
        ];

        // 示例:查询构造器原生查询,无Model也可直接操作表
        // $exportData = \DB::table('your_table')->where('status', 1)->get()->toArray();

        $headings = ['序号', '姓名', '手机号'];

        return Excel::download(new ExportExcel($exportData, $headings), '导出文件.xlsx');
    }
}

路由配置(routes/web.php)

use App\Http\Controllers\ExportController;

Route::get('/export-excel', [ExportController::class, 'export'])->name('export.excel');

3. 前端下载按钮

Blade模板中直接添加跳转链接即可:

<a href="{{ route('export.excel') }}" class="btn btn-primary">导出Excel</a>

<!-- 带筛选条件导出示例 -->
<!-- <a href="{{ route('export.excel', ['keyword' => '筛选关键词']) }}" class="btn btn-primary">按条件导出</a> -->

内容的提问来源于stack exchange,提问作者green matcha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 22:45:08