laravel excel导入导出

一、安装第三方

composer require maatwebsite/excel

版本2.1和现在版本 有所不一样

二、导入


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)
        {
        	//处理数据
        }
	}

}

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);
	}
}

三、导出


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;
    }
}

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,配置生成文件的地址

    'local_path'          => public_path().'/error_excel/',

你可能感兴趣的:(laravel)