Wilber / Wilbercsv
一个用于从 Eloquent 模型轻松生成 CSV 文件的 Laravel 扩展包。
Requires
- php: >=5.6.4
- illuminate/database: >=5.2
- league/csv: >=8.2
Requires (Dev)
- fzaninotto/faker: ^1.6
- phpunit/phpunit: 5.7.*
This package is not auto-updated.
Last update: 2024-09-20 21:17:10 UTC
README
一个用于从 Eloquent 模型轻松生成 CSV 文件的 Laravel 扩展包。
基本用法
$users = User::get(); // All users $csvExporter = new \Laracsv\Export(); $csvExporter->build($users, ['email', 'name'])->download();
并且将下载一个包含 email
和 name
字段的合适的 CSV 文件。
安装
只需在终端运行以下命令
composer require "wilber/wilbercsv"
然后您就可以开始使用了。
完整文档
构建 CSV
$exporter->build($modelCollection, $fields)
接收两个参数。第一个是模型(模型集合),第二个参数接收要导出的字段名。
$csvExporter->build(User::get(), ['email', 'name', 'created_at']);
输出选项
下载
要获取浏览器下载的文件
$csvExporter->download();
您可以选择提供文件名
$csvExporter->download('active_users.csv');
如果没有提供文件名,将生成包含日期时间的文件名。
高级输出
LaraCSV 使用 League CSV。您可以执行 League CSV 可以执行的操作。您可以通过调用
$csv = $csvExporter->getCsv();
来获取底层的 League CSV 实例。
$csv->toHTML(); // To output the CSV as an HTML table $csv->jsonSerialize()(); // To turn the CSV in to an array $csv = (string) $csv; // To get the CSV as string echo $csv; // To print the CSV
然后您可以执行多个操作,例如
自定义表头
有关更多信息,请参阅 League CSV 文档。
上面的代码示例将生成一个包含标题 email、name、created_at 以及相应的行的 CSV。
$csvExporter->build(User::get(), ['email', 'name' => 'Full Name', 'created_at' => 'Joined']);
如果您想使用自定义标签更改标题,只需将其作为数组值传递
修改或添加值
现在 name
列将显示标题 Full Name
,但它仍然从模型的 name
字段获取值。
$csvExporter = new \Laracsv\Export(); $users = User::get(); // Register the hook before building $csvExporter->beforeEach(function ($user) { $user->created_at = date('f', strtotime($user->created_at)); }); $csvExporter->build($users, ['email', 'name' => 'Full Name', 'created_at' => 'Joined']);
注意:如果 beforeEach
回调返回 false
,则整个数据将排除在 CSV 之外。这在过滤某些行时可能很有用。
添加字段和值
您还可以添加不存在于数据库表中的字段并动态添加值
// The notes field doesn't exist so values for this field will be blank by default $csvExporter->beforeEach(function ($user) { // Now notes field will have this value $user->notes = 'Add your notes'; }); $csvExporter->build($users, ['email', 'notes']);
模型关系
您还可以从相关数据库表中添加字段到 CSV,前提是该模型已定义了关系。
这将获取产品标题和相关的分类标题(一对一)
$csvExporter->build($products, ['title', 'category.title']);
您还可以使用钩子按您想要的任何方式调整关系
$products = Product::where('order_count', '>', 10)->orderBy('order_count', 'desc')->get(); $fields = ['id', 'title','original_price' => 'Market Price', 'category_ids',]; $csvExporter = new \Laracsv\Export(); $csvExporter->beforeEach(function ($product) { $product->category_ids = implode(', ', $product->categories->pluck('id')->toArray()); });
路线图
- 导入 CSV