dev-pirate / lara-excel-craft
Laravel 包用于导出/导入 Excel 表格
v1.0.5
2024-01-09 17:11 UTC
Requires
- php: ^8.1
- ext-json: *
- barryvdh/laravel-cors: *
- phpoffice/phpspreadsheet: ^1.29
Requires (Dev)
- mockery/mockery: ^1.2
- orchestra/testbench: ^3.7
README
LaraExcelCraft 是一个 Laravel 扩展包,使用 antd 组件、ReactJs 和 PhpSpreadsheet,方便地逐步将 Excel 文件导入/导出到数据库表,并拥有友好的界面。
通过 composer 安装
运行以下命令以拉取最新版本
composer require dev-pirate/lara-excel-craft
发布配置
运行以下命令以发布包配置文件
php artisan vendor:publish --provider="DevPirate\LaraExcelCraft\Providers\LaraExcelCraftProvider"
现在你应该有一个 config/lara-excel-craft.php 文件,该文件允许你配置此包的基本设置。
添加路由
在您的路由文件中添加以下代码
Route::middleware([ 'api', \Fruitcake\Cors\HandleCors::class, ])->group(function() { LaraExcelCraft::routes(); }); // \Fruitcake\Cors\HandleCors middleware are required here to manage cors
添加视图
- 将导入组件添加到您的视图中
<x-lara-excel-craft::lara-excel-import-sheet />
- 将导出组件添加到您的视图中
<x-lara-excel-craft::lara-excel-export-sheet />
自定义 Excel 导入
在继续之前,请确保您已按照 Laravel 的安装说明安装了此包。
更新您的用户模型
首先,您需要在您的模型上实现 DevPirate\LaraExcelCraft\Interfaces\ExcelManager 接口,这需要自定义数据导入逻辑,您需要实现 importDataFromExcel(array $data) 和 getImportableFields() 以及 exportDataToExcel() 这三个方法。
以下示例应能为您提供一些思路。显然,您应根据需要做出任何必要的更改。
<?php namespace App\Models; use Carbon\Carbon; use DevPirate\LaraExcelCraft\Interfaces\ExcelManager; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Example extends Model implements ExcelManager { use HasFactory; protected $fillable = [ 'orderDate', 'region', 'rep', 'item', 'unit', 'total', 'created_at', 'updated_at', ]; public static function importDataFromExcel(array $data): void { // this can be customized, it depends on your logic // this is just an example $data = array_map(function ($item) { return [ ...$item, 'total' => floatval($item['total'] ?? 0), 'unit' => intval($item['unit'] ?? 0), 'orderDate' => $item['orderDate'] ? Carbon::createFromFormat('d/m/Y', trim($item['orderDate'])): null, 'created_at' => now(), 'updated_at' => now(), ]; }, $data); self::insert($data); } public static function getImportableFields(): array { // return an array of the table fields that could be importable from excel return [ 'orderDate', 'region', 'rep', 'item', 'unit', 'total' ]; } public static function exportDataFromExcel(): array { // this can be customized depend on your logic return array_map(function ($item) { return array_merge($item, [ 'orderDate' => Carbon::parse($item['orderDate'])->format('d/m/Y') ?? '' ]); }, self::all()->toArray()); } }
配置文件
让我们回顾一下之前发布的 config/lara-excel-craft.php 文件中的一些选项。
首先是
<?php return [ // storage disk name where the uploaded temp excel files are going to be stored 'fileTempDisk' => 'local', // path where your application models classes are stored 'models_path' => app_path('Models'), // route name where you want the application to redirect you after importing the data with excel sheet 'redirectTo' => 'home' // other configuration parameters ];
.