Laravel如何指定路径导出Excel文件?实现无模型导出
在Laravel中不使用Model导出Excel的实现方案
你可以完全脱离Eloquent Model,通过自定义数据集合/数组,或者直接操作PhpSpreadsheet实例来实现Excel导出,以下是两种常用的实现方式:
方式一:用自定义数据集合快速导出(推荐)
这种方式利用Laravel Excel的FromCollection和WithHeadings接口,直接返回你需要导出的数据,无需关联任何Model:
修改UserExportExcel类
use Maatwebsite\Excel\Concerns\FromCollection; use Maatwebsite\Excel\Concerns\WithHeadings; use Illuminate\Support\Collection; class UserExportExcel implements FromCollection, WithHeadings { private $id; public function __construct(int $id) { $this->id = $id; } // 定义Excel表头 public function headings(): array { return [ '用户ID', '用户名', '邮箱', '创建时间' ]; } // 返回要导出的数据集(无需Model) public function collection() { // 示例1:直接构造自定义数据 $customData = [ [1, '张三', 'zhangsan@test.com', '2024-01-01'], [2, '李四', 'lisi@test.com', '2024-01-02'] ]; // 示例2:如果需要从数据库取数,用DB门面直接查询(不用Model) // $customData = DB::table('users')->where('group_id', $this->id)->select('id', 'name', 'email', 'created_at')->get(); return collect($customData); } }
路由代码保持不变
Route::get('UserExport', function (UserRequest $request) { return Excel::download(new UserExportExcel($request->id), 'UserReport.xlsx'); });
方式二:直接操作PhpSpreadsheet(复杂场景适用)
如果需要自定义Excel样式、合并单元格等复杂操作,可以直接实例化PhpSpreadsheet对象,完全手动控制导出内容:
修改UserExportExcel类
use Maatwebsite\Excel\Concerns\WithEvents; use Maatwebsite\Excel\Events\BeforeWriting; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Writer\Xlsx; use PhpOffice\PhpSpreadsheet\Style\Alignment; class UserExportExcel implements WithEvents { private $id; public function __construct(int $id) { $this->id = $id; } public function registerEvents(): array { return [ BeforeWriting::class => function(BeforeWriting $event) { $spreadsheet = new Spreadsheet(); $sheet = $spreadsheet->getActiveSheet(); // 设置表头并添加样式 $sheet->setCellValue('A1', '用户ID'); $sheet->setCellValue('B1', '用户名'); $sheet->setCellValue('C1', '邮箱'); $sheet->getStyle('A1:C1')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER); // 填充自定义数据 $data = [ [1, '张三', 'zhangsan@test.com'], [2, '李四', 'lisi@test.com'] ]; $row = 2; foreach ($data as $item) { $sheet->setCellValue('A' . $row, $item[0]); $sheet->setCellValue('B' . $row, $item[1]); $sheet->setCellValue('C' . $row, $item[2]); $row++; } $event->writer = new Xlsx($spreadsheet); }, ]; } }
额外说明
- 如果需要将Excel保存到服务器指定路径,而非浏览器下载,可替换路由中的
Excel::download为Excel::store:
Route::get('UserExport', function (UserRequest $request) { $filePath = storage_path('app/Users/' . $request->id . '.xlsx'); Excel::store(new UserExportExcel($request->id), $filePath); return response()->json(['msg' => '文件已成功保存到指定路径'], 200); });
- 数据来源可以是任意渠道:自定义数组、数据库原生查询、外部API返回数据、本地文件读取结果等,只要能整理成数组/集合格式即可。
内容的提问来源于stack exchange,提问作者Mohammad Mansour
相关产品推荐
相关产品推荐

