Laravel导出百万数据

 $time = time();
        $dir_path = public_path('orderlog');
        if (!is_dir($dir_path))
            mkdir($dir_path, 0777, true);
        // 文件名
        $fileName = date('Ymd') . '.csv';
        //  检测文件是否已存在
        if (file_exists($dir_path . '/' . $fileName))
            unlink($dir_path . '/' . $fileName);
        // 打开文件
        $myfile = fopen($dir_path . '/' . $fileName, "w") or die("Unable to open file!");

        $title = ['日志ID', '订单号',  '用户名', '标题', '内容', '添加时间'];
        $head = mb_convert_encoding($title, 'GBK', 'utf-8');
        fwrite($myfile, $head);
        $rows = DB::table('order_log');
        $this->output->progressStart($rows->count());
        $rows->chunkById(1000, function($items) use (&$myfile) {
            foreach ($items as $item) {
                $this->output->progressAdvance();
                $data = [
                    $item->log_id,$item->order_md5,$item->username,$item->title,$item->content,date('Y-m-d', $item->add_time)
                ];
                fputcsv($myfile, $data);
            }
        }, 'log_id');

        $this->output->progressFinish();
        $endTime = time();
        $t = round(($endTime - $time) / 60);
        $this->info("共耗时:".$t."分钟");

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在 Laravel导出 Excel,你可以使用 Laravel Excel 这个扩展包。下面是简单的步骤: 1. 使用 Composer 安装 Laravel Excel ``` composer require maatwebsite/excel ``` 2. 在 `config/app.php` 文件中添加服务提供者和门面 ```php 'providers' => [ // ... Maatwebsite\Excel\ExcelServiceProvider::class, ], 'aliases' => [ // ... 'Excel' => Maatwebsite\Excel\Facades\Excel::class, ], ``` 3. 创建控制器和视图 创建一个控制器来处理 Excel 导出的逻辑,例如 `ExcelController`,并在其中创建一个 `export()` 方法来生成 Excel 表格。 ```php namespace App\Http\Controllers; use Illuminate\Http\Request; use Maatwebsite\Excel\Facades\Excel; use App\Exports\UsersExport; class ExcelController extends Controller { public function export() { return Excel::download(new UsersExport, 'users.xlsx'); } } ``` 在 `app/Exports` 目录下创建一个 `UsersExport` 类,用于生成 Excel 数据。 ```php namespace App\Exports; use App\User; use Maatwebsite\Excel\Concerns\FromCollection; class UsersExport implements FromCollection { public function collection() { return User::all(); } } ``` 创建一个视图文件来呈现导出 Excel 表格的按钮,例如 `export.blade.php`。 ```html <a href="{{ route('export') }}">Export Users</a> ``` 4. 定义路由 在 `routes/web.php` 文件中定义一个路由,指向 `ExcelController` 的 `export()` 方法。 ```php Route::get('export', 'ExcelController@export')->name('export'); ``` 现在,当用户访问 `/export` 路径时,会生成一个名为 `users.xlsx` 的 Excel 文件,包含用户数据

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值