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

LaravelExcel Maatwebsite导出无数据问题求助

Laravel 5.8 + Laravel Excel 导出空文件问题解决

我在Laravel 5.8项目中使用Maatwebsite/Laravel Excel实现从数据库导出数据到Excel,但下载的文件内容为空,以下是我的代码实现:

模型中的方法

public static function getAllData()
{
    $records = DB::table('orders')->select('ord_id','ord_date','ord_total')->get()->toArray(); 
}

导出类

class OrderAllDataExport implements FromCollection, WithHeadings
{
    public function headings():array
    {
        return [
            'ID',
            'Date',
            'Total',
        ];
    }
    
    public function collection()
    {
        return collect(Order::getAllData());
    }
}

控制器方法

public function exportAllDataIntoExcel()
{
    return Excel::download(new OrderAllDataExport,'orders_all.xlsx');
}

路由配置

Route::get('export/data/list/orders' , 'OrdersController@exportAllDataIntoExcel')->name('exportAllDataIntoExcel');

测试时Excel文件可正常下载,但内容为空:
导出的空Excel文件


问题原因

模型中的getAllData方法仅定义了$records变量,但没有返回该变量,导致Order::getAllData()返回null,最终collect(null)生成空集合,Excel自然没有数据。

解决方法

修改模型中的getAllData方法,添加返回语句:

public static function getAllData()
{
    return DB::table('orders')->select('ord_id','ord_date','ord_total')->get()->toArray(); 
}

更优写法:无需转成数组,直接返回查询结果集合(Laravel Excel原生支持处理集合),同时简化导出类代码:

  1. 模型方法修改:
public static function getAllData()
{
    return DB::table('orders')->select('ord_id','ord_date','ord_total')->get(); 
}
  1. 导出类的collection方法简化:
public function collection()
{
    return Order::getAllData();
}

内容的提问来源于stack exchange,提问作者Pouya Vaghefi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 08:25:27