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文件可正常下载,但内容为空:
问题原因
模型中的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原生支持处理集合),同时简化导出类代码:
- 模型方法修改:
public static function getAllData() { return DB::table('orders')->select('ord_id','ord_date','ord_total')->get(); }
- 导出类的
collection方法简化:
public function collection() { return Order::getAllData(); }
内容的提问来源于stack exchange,提问作者Pouya Vaghefi
相关产品推荐
相关产品推荐

