環境
安裝套件
安裝 phpoffice/phpspreadsheet 套件。
| 1
 | composer require phpoffice/phpspreadsheet
 | 
設計
- 建立一個獨立的 ExcelGenerator 模組,只負責資料處理與檔案輸出。
修改 composer.json 檔
使用 PSR-4 方法自動加載命名空間。
| 12
 3
 4
 5
 
 | "autoload": {"psr-4": {
 "Application\\Controllers\\Module\\": "application/controllers/module/"
 }
 }
 
 | 
執行傾倒
使用
資料注入
| 12
 3
 4
 5
 6
 7
 8
 9
 
 | use Application\Controllers\Module\ExcelGenerator;
 
 
 $result = [];
 
 $excel = new ExcelGenerator();
 
 $excel->myFunc($result);
 
 | 
檔案生成
建立 application/controllers/module/ExcelGenerator.php 檔。
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 
 | namespace Application\Controllers\Module;
 
 
 use PhpOffice\PhpSpreadsheet\IOFactory;
 use PhpOffice\PhpSpreadsheet\Spreadsheet;
 
 class ExcelGenerator
 {
 public function myFunc($result) {
 
 $file_name = 'foo';
 
 
 $spreadsheet = new Spreadsheet();
 
 $sheet = $spreadsheet->getActiveSheet()->fromArray($data);
 
 
 header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
 header('Content-Disposition: attachment;filename="' . $file_name . '.xlsx"');
 header('Cache-Control: max-age=0');
 
 
 $writer = IOFactory::createWriter($sheet, 'Xlsx');
 $writer->save('php://output');
 }
 }
 
 
 |