overlu / mini-excel
Mini的Excel导入/导出
v1.0.0
2024-05-16 10:29 UTC
Requires
- php: ^8.1
- openspout/openspout: ^4.19
- overlu/mini-framework: ~3.2.0
- symfony/http-foundation: ^6.4
README
感谢 rap2hpoutre/fast-excel 提供了优秀的扩展,具体使用说明请传送至 https://github.com/rap2hpoutre/fast-excel
快速开始
使用composer安装
composer require overlu/mini-excel
导出模型到 .xlsx
文件
use MiniExcel\Excel; use App\Models\User; // Load users $users = User::all(); // Export all users (new Excel($users))->export('file.xlsx');
导出
导出模型或 集合
$list = collect([ [ 'id' => 1, 'name' => 'Jane' ], [ 'id' => 2, 'name' => 'John' ], ]); (new Excel($list))->export('file.xlsx');
导出 xlsx
,ods
和 csv
$invoices = App\Invoice::orderBy('created_at', 'DESC')->get(); (new Excel($invoices))->export('invoices.csv');
指定列名仅导出某些属性
(new Excel(User::all()))->export('users.csv', function ($user) { return [ 'Email' => $user->email, 'First Name' => $user->firstname, 'Last Name' => strtoupper($user->lastname), ]; });
下载(从控制器方法中)
return (new Excel(User::all()))->download('file.xlsx');
导入
import
返回一个集合
$collection = (new Excel)->import('file.xlsx');
导入具有特定分隔符、封装字符和 "gbk" 编码的 csv
$collection = (new Excel)->configureCsv(';', '#', 'gbk')->import('file.csv');
导入并插入到数据库
$users = (new Excel)->import('file.xlsx', function ($line) { return User::create([ 'name' => $line['Name'], 'email' => $line['Email'] ]); });
外观
使用外观,您将无法访问构造函数。您可以使用 data
方法设置您的导出数据。
$list = collect([ [ 'id' => 1, 'name' => 'Jane' ], [ 'id' => 2, 'name' => 'John' ], ]); Excel::data($list)->export('file.xlsx');
全局助手
Excel提供了一个方便的全局助手,可以在Laravel应用程序的任何地方快速实例化Excel类。
$collection = Excel()->import('file.xlsx'); Excel($collection)->export('file.xlsx');
高级用法
导出多个工作表
通过创建 SheetCollection
导出多个工作表
$sheets = new SheetCollection([ User::all(), Project::all() ]); (new Excel($sheets))->export('file.xlsx');
使用索引指定工作表名称
$sheets = new SheetCollection([ 'Users' => User::all(), 'Second sheet' => Project::all() ]);
导入多个工作表
使用 importSheets
导入多个工作表
$sheets = (new Excel)->importSheets('file.xlsx');
您也可以通过其编号导入特定的工作表
$users = (new Excel)->sheet(3)->import('file.xlsx');
通过工作表名称导入多个工作表
$sheets = (new Excel)->withSheetsNames()->importSheets('file.xlsx');
使用分块导出大型集合
逐行导出行以避免 memory_limit
问题 使用 yield
function usersGenerator() { foreach (User::cursor() as $user) { yield $user; } } // Export consumes only a few MB, even with 10M+ rows. (new Excel(usersGenerator()))->export('test.xlsx');
添加标题和行样式
使用 headerStyle
和 rowsStyle
方法添加标题和行样式。
use OpenSpout\Common\Entity\Style\Style; $header_style = (new Style())->setFontBold(); $rows_style = (new Style()) ->setFontSize(15) ->setShouldWrapText() ->setBackgroundColor("EDEDED"); return (new Excel($list)) ->headerStyle($header_style) ->rowsStyle($rows_style) ->download('file.xlsx');
为什么?
Excel旨在成为Laravel风味的 Spout:一个简单而优雅的包装,其目标是在不牺牲性能的情况下简化 导入和导出。它可以被认为是一个更快的(且内存友好的)替代方案(Laravel Excel),具有更少的功能。仅用于简单任务。
基准测试
在2015年MacBook Pro 2.7 GHz Intel Core i5 16 Go 1867 MHz DDR3上测试。测试10000行,20列随机数据的XLSX导出,10次迭代,2018-04-05。不要相信基准测试。
仍然,记住 Laravel Excel 有更多功能。