一、安装第三方
composer require maatwebsite/excel
版本2.1和现在版本 有所不一样文章来源:https://www.toymoban.com/news/detail-692559.html
二、导入
<?php
namespace App\Import;
use Maatwebsite\Excel\Concerns\ToCollection;
class TestImport implements ToCollection
{
public function __construct()
{
}
public function collection(Collection $collection)
{
//处理导入文件的数据,完成内部业务数据逻辑
unset($collection[0]);
foreach ($collection as $key=>$row)
{
//处理数据
}
}
}
<?php
namespace App\Http\Controller;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Import\TestImport;
use Maatwebsite\Excel\Facades\Excel;
class TestController extends Controller
{
public function test(Request $request)
{
$path1 = $request->file('file')->store('temp');
$path = storage_path('app').'/'.$path1;
Excel::import(new TestImport(),$path);
}
}
三、导出
<?php
namespace App\Derive;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\WithHeadings;
class TestDerive implements FromCollection, WithHeadings
{
use Exportable;
private $data;
private $headings;
//数据注入
public function __construct($data, $headings)
{
$this->data = $data;
$this->headings = $headings;
}
//实现FromCollection接口
public function collection()
{
return collect($this->data);
}
//实现WithHeadings接口
public function headings(): array
{
return $this->headings;
}
}
<?php
namespace App\Http\Controller;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Import\TestImport;
use Maatwebsite\Excel\Facades\Excel;
use App\Derive\TestDerive;
use Illuminate\Support\Facades\File;
class TestController extends Controller
{
public function test()
{
//自定义导出的数据
arrErrorInfo = [];
//导出的文件表头信息
$head = [
'uid','reason'
];
//根据数据生成的excel文件地址 自定义
$publicpath = date('Y-m-d',time()).'/test.xls';
//如果这个地址前面有日期的区分,需要判断文件夹赋予文件权限
if ( !File::isDirectory(date('Y-m-d',time())) )
File::makeDirectory(date('Y-m-d',time()), $mode = 0777, true, true);
$bRet = Excel::store(new AvatarExcel($arrErrorInfo, $head), $publicpath);
//todo 判断生成的文件是否为真,根据业务处理
}
}
config配置文件夹中excel.php,配置生成文件的地址文章来源地址https://www.toymoban.com/news/detail-692559.html
'local_path' => public_path().'/error_excel/',
到了这里,关于laravel excel导入导出的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!