Laravel 5.4使用Maatwebsite/Excel导出Excel报错,求解决方案
Hey there, let's get this Excel export issue sorted out for you! That error message is pointing straight to the root of the problem—we're passing a non-array value to a method that strictly expects an array.
What's Causing the Error?
Your line $export = Student::all(); returns an Eloquent Collection object, not a plain PHP array. When you pass this collection directly to $sheet->fromArray(), the underlying code tries to process it as an array but ends up passing a mismatched type to Builder::create(), triggering that type error.
The Simple Fix
All we need to do is convert that Eloquent Collection into a native PHP array using the built-in toArray() method:
Corrected Full Code
// Convert the collection to a plain array first $export = Student::all()->toArray(); Excel::create('Export Excel',function($excel) use($export){ $excel->sheet('Sheet 1', function($sheet) use($export){ $sheet->fromArray($export); }); })->download('xlsx');
Bonus: Customize Your Exported Fields
If you don't need every column from your students table in the export, you can specify exactly which fields to include before converting to an array—this makes your export cleaner and more efficient:
// Select only the fields you want to export, then convert to array $export = Student::select('id', 'name', 'email', 'enrollment_date')->get()->toArray();
This adjustment ensures the fromArray() method gets the data format it needs, and you'll be able to download your Excel file without any errors.
内容的提问来源于stack exchange,提问作者JustMeNad

