laravel8 简单Excel导入、导出

如果没有安装laravel8,我们可以去官网有安装方式

直接到项目根目录composer安装maatwebsite/excel包

composer require maatwebsite/excel

安装完成后就可以做操作了

创建导入类

php artisan make:import UsersImport --model=User

找到生成的文件

app/Imports/UsersImport.php

  
namespace App\Imports;
  
use App\Models\User;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
  
class UsersImport implements ToModel, WithHeadingRow
{
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function model(array $row)
    {
    	//导入的数据
        return new User([
            'name'     => $row['name']'email'    => $row['email']'password' => \Hash::make($row['password'])]);
    }
}

创建导出类

php artisan make:export UsersExport --model=User

找到生成的文件

app/Exports/UsersExport.php

  
namespace App\Exports;
  
use App\Models\User;
use Maatwebsite\Excel\Concerns\FromCollection;
  
class UsersExport implements FromCollection
{
    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
    //导出的模型数据
        return User::all();
    }
}

控制器方法


     
namespace App\Http\Controllers;
    
use Illuminate\Http\Request;
use App\Exports\UsersExport;
use App\Imports\UsersImport;
use Maatwebsite\Excel\Facades\Excel;
    
class MyController extends Controller
{
     
    /**
    * @return \Illuminate\Support\Collection
    */
    public function export() 
    {
    	//导出方法
        return Excel::download(new UsersExport'users.xlsx');
    }
     
    /**
    * @return \Illuminate\Support\Collection
    */
    public function import() 
    {
    	//导入方法
        Excel::import(new UsersImportrequest()->file('file'));
             
        return back();
    }
}

你可能感兴趣的:(laravel,php,excel)