bayareawebpro / laravel-simple-csv
Laravel 的简单 CSV 导入/导出工具。
v2.2.0
2024-06-04 03:00 UTC
Requires
- php: ^7.2|^8.0
- illuminate/support: ^6.0|^7.0|^8.0|^9.0|^10.0|^11.0
Requires (Dev)
- larastan/larastan: ^1.0|^2.0
- orchestra/testbench: ^4.0|^5.0|^6.0|^7.0|^8.0|^9.0
- phpunit/phpunit: ^8.0|^9.0|^10.0|^11.0
README
https://packagist.org.cn/packages/bayareawebpro/laravel-simple-csv
功能
- 导入到 LazyCollection。
- 从 Collection、LazyCollection、Iterable、Generator、Array 导出。
- 通过使用 LazyCollection 生成器降低(更低)内存消耗。
- 使用原生 PHP SplFileObject。
- 包含 Facade。
安装
需要此包,Laravel 将自动发现服务提供者。
composer require bayareawebpro/laravel-simple-csv
用法
可以将可调用类传递给导入方法,以便您自定义处理每行的方式。已提供两个类来处理数值和空值。
use BayAreaWebPro\SimpleCsv\SimpleCsv; use BayAreaWebPro\SimpleCsv\Casts\EmptyValuesToNull; use BayAreaWebPro\SimpleCsv\Casts\NumericValues; $lazyCsvCollection = SimpleCsv::import(storage_path('collection.csv'), [ EmptyValuesToNull::class, NumericValues::class, ]);
可调用类
依赖注入:当定义时,可调用类可以在构造方法中为所需依赖项使用类型提示。
<?php declare(strict_types=1); namespace App\Csv\Casts; use Carbon\Carbon; class Timestamps { /** Invoked for each row in import collection. */ public function __invoke(array $item): array { foreach ($item as $key => $value){ if(in_array($key, ['created_at', 'updated_at'])){ $item[$key] = Carbon::parse($value); } } return $item; } }
导出到文件
use BayAreaWebPro\SimpleCsv\SimpleCsv; // Collection SimpleCsv::export( Collection::make(...), storage_path('collection.csv') ); // LazyCollection SimpleCsv::export( LazyCollection::make(...), storage_path('collection.csv') ); // Generator (Cursor) SimpleCsv::export( User::query()->where(...)->limit(500)->cursor(), storage_path('collection.csv') ); // Array SimpleCsv::export( [...], storage_path('collection.csv') );
导出下载流
use BayAreaWebPro\SimpleCsv\SimpleCsv; return SimpleCsv::download([...], 'download.csv');
重写选项
use Illuminate\Support\Facades\Config; Config::set('simple-csv.delimiter', ...); Config::set('simple-csv.enclosure', ...); Config::set('simple-csv.escape', ...);
或者,创建一个配置文件
config/simple-csv.php
return [ 'delimiter' => '?', 'enclosure' => '?', 'escape' => '?', ];
文件分割实用工具
包含一个文件分割实用工具,可以将大型 CSV 文件拆分为块(同时保留列标题),您可以在导入后移动/删除这些块。这可以帮助自动化导入大型数据集。
提示:查找您的 Bash Shell 二进制路径:which sh
/bin/sh vendor/bayareawebpro/laravel-simple-csv/split-csv.sh /Projects/laravel/storage/big-file.csv 5000
File Output:
/Projects/laravel/storage/big-file-chunk-1.csv (chunk of 5000)
/Projects/laravel/storage/big-file-chunk-2.csv (chunk of 5000)
/Projects/laravel/storage/big-file-chunk-3.csv (chunk of 5000)
etc...
速度提示
- 使用 Lazy Collections 是首选方法。
- 使用队列工作进程,您可以一次导入数千行,影响不大。
- 请确保使用“数据库事务”和“超时检测”以确保安全导入。
- 文章:如何一次性插入和更新多个数据