使用 Laravel-Excel 和流的方法导出 Excel
阅读原文时间:2023年07月11日阅读:1

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