1、使用 laravel-excel 擴展包導出
擴展包的 3.0 的版本和 2.0 相比做了很多的改動,個人感覺更容易使用了。擴展包給出了很多基於 query 的導出,視圖的導出。下面例子為基於 array 的導出,其他的查看文檔即可。
導出類:
use Maatwebsite\Excel\Concerns\FromCollection; use Maatwebsite\Excel\Concerns\Exportable; use Maatwebsite\Excel\Concerns\WithHeadings; class UsersExport implements FromCollection, WithHeadings { use Exportable; private $data; private $headings; //數據注入 public function __construct($data, $headings) { $this->data = $data; $this->headings = $headings; } //實現FromCollection接口 public function collection() { return collect($this->data); } //實現WithHeadings接口 public function headings(): array { return $this->headings; } }
控制器中導出
namespace App\Http\Controllers; use Maatwebsite\Excel\Facades\Excel; use App\Exports\UsersExport; class UsersController extends Controller { public function export() { $data = [ [ 'name' => 'cheng', 'email' => 'cheng111' ], [ 'name' => 'cheng', 'email' => 'cheng111' ], ]; $headings = [ 'name', 'email' ]; return Excel::download(new UsersExport($data, $headings), 'users.csv'); } }
2、使用流的形式導出
public function export($params) { set_time_limit(0); $columns = ['字段名']; $fileName = 'GPS管理明細' . '.csv'; //設置好告訴瀏覽器要下載excel文件的headers header('Content-Description: File Transfer'); header('Content-Type: application/vnd.ms-excel'); header('Content-Disposition: attachment; filename="'. $fileName .'"'); header('Expires: 0'); header('Cache-Control: must-revalidate'); header('Pragma: public'); $fp = fopen('php://output', 'a');//打開output流 mb_convert_variables('GBK', 'UTF-8', $columns); fputcsv($fp, $columns); //將數據格式化為CSV格式並寫入到output流中 $num = $this->getExportNum($params); $perSize = 2000;//每次查詢的條數 $pages = ceil($num / $perSize); for($i = 1; $i <= $pages; $i++) { $list = $this->getUnitExportData($params, $i, $perSize); foreach($list as $item) { $rowData[] = $this->switchDeviceMakerToDesc($item['device_maker']); . . . mb_convert_variables('GBK', 'UTF-8', $rowData); fputcsv($fp, $rowData); unset($rowData); } unset($accessLog);//釋放變量的內存 ob_flush(); //刷新輸出緩沖到瀏覽器 flush(); //必須同時使用 ob_flush() 和flush() 函數來刷新輸出緩沖。 } fclose($fp); exit(); }
原文:https://learnku.com/articles/17829