gito-me / fast-excel
Requires
- php: ^7.0
- box/spout: ^2.7
- laravel/framework: ^5.0
Requires (Dev)
- phpunit/phpunit: ^6.4
This package is not auto-updated.
Last update: 2024-09-27 14:09:03 UTC
README
Fast Excel 为 Laravel 提供快速导入/导出功能,得益于 Spout。以下为基准测试结果。
快速开始
通过 composer 安装
composer require rap2hpoutre/fast-excel
将模型导出到 .xlsx
文件
use Rap2hpoutre\FastExcel\FastExcel; use App\User; // Load users $users = User::all(); // Export all users (new FastExcel($users))->export('file.xlsx');
导出
导出模型或 集合
$list = collect([ [ 'id' => 1, 'name' => 'Jane' ], [ 'id' => 2, 'name' => 'John' ], ]); (new FastExcel($list))->export('file.xlsx');
导出 xlsx
、ods
和 csv
$invoices = App\Invoice::orderBy('created_at', 'DESC')->get(); (new FastExcel($invoices))->export('invoices.csv');
指定列名以仅导出某些属性
(new FastExcel(User::all()))->export('users.csv', function ($user) { return [ 'Email' => $user->email, 'First Name' => $user->firstname, 'Last Name' => strtoupper($user->lastname), ]; });
下载(从控制器方法中)
return (new FastExcel(User::all()))->download('file.xlsx');
导入
import
返回一个集合
$collection = (new FastExcel)->import('file.xlsx');
导入具有特定分隔符、封装字符和 "gbk" 编码的 csv
$collection = (new FastExcel)->configureCsv(';', '#', '\n', 'gbk')->import('file.csv');
导入并插入到数据库中
$users = (new FastExcel)->import('file.xlsx', function ($line) { return User::create([ 'name' => $line['Name'], 'email' => $line['Email'] ]); });
门面
您可以选择使用 FastExcel 的 Facade。将以下行添加到 config/app.php
中的 aliases
键下。
'FastExcel' => Rap2hpoutre\FastExcel\Facades\FastExcel::class,
使用 Facade,您将无法访问构造函数。您可以使用 data
方法设置您的导出数据。
$list = collect([ [ 'id' => 1, 'name' => 'Jane' ], [ 'id' => 2, 'name' => 'John' ], ]); FastExcel::data($list)->export('file.xlsx');
全局助手
FastExcel 为 Laravel 应用程序中任何位置的快速实例化 FastExcel 类提供了方便的全局助手。
$collection = fastexcel()->import('file.xlsx'); fastexcel($collection)->export('file.xlsx');
高级用法
导出多个工作表
通过创建 SheetCollection
导出多个工作表
$sheets = new SheetCollection([ User::all(), Project::all() ]); (new FastExcel($sheets))->export('file.xlsx');
使用索引指定工作表名称
$sheets = new SheetCollection([ 'Users' => User::all(), 'Second sheet' => Project::all() ]);
导入多个工作表
通过使用 importSheets
导入多个工作表
$sheets = (new FastExcel)->importSheets('file.xlsx');
您还可以通过其编号导入特定的工作表
$users = (new FastExcel)->sheet(3)->import('file.xlsx');
为什么?
FastExcel 致力于成为具有 Laravel 风格的 Spout:一个简单但优雅的包装器,目的是简化 导入和导出。
它可以被认为是 Laravel Excel 的更快的(且内存友好)替代品,具有 更少的 功能。仅用于非常简单的任务。
基准测试
在 MacBook Pro 2015 2,7 GHz Intel Core i5 16 Go 1867 MHz DDR3 上进行测试。2018-04-05 对 10000 行,20 列的随机数据进行 XLSX 导出测试,10 次迭代。 不要相信基准测试。
然而,请记住 Laravel Excel 有更多的功能。请帮助我改进基准测试,更多测试即将到来。请随意批评。