Laravel 导入 导出

引用插件https://github.com/Maatwebsite/Laravel-Excel

插件

1.安装
composer require maatwebsite/excel
2.修改文件config/app.php
'providers' => [
    /*
     * Package Service Providers...
     */
    Maatwebsite\Excel\ExcelServiceProvider::class,
]

'aliases' => [
    ...
    'Excel' => Maatwebsite\Excel\Facades\Excel::class,
]
3.发布配置
php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider"
支持中文

修改config/excel.php配置文件

'imports'            => [

        'read_only' => true,

        'heading_row' => [

            /*
            |--------------------------------------------------------------------------
            | Heading Row Formatter
            |--------------------------------------------------------------------------
            |
            | Configure the heading row formatter.
            | Available options: none|slug|custom
            |
            */
            'formatter' => 'custom',
        ],
    ],

导入

<?php

namespace App\Imports;

use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithMultipleSheets;

class UsersImport implements ToModel, WithHeadingRow, WithMultipleSheets
{
    public function model(array $row)
    {

        if (!isset($row['姓名'])) {
            return null;
        }

        return new User(
            [
                'name'   => $row['姓名'],
                'mobile' => $row['手机'],
            ]
        );
    }

    public function sheets(): array
    {
        return [
            // Select by sheet index
            0 => new UsersImport(),
        ];
    }
}

导出

<?php
namespace App\Exports;

use App\Models\News;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithHeadings;

class NewsExport implements FromQuery, WithMapping, WithHeadings
{
    /**
    * @return \Illuminate\Support\Collection
    */
    public function query()
    {
        return News::query();
    }

    /**
    * @var Product $item
    */
    public function map($item): array
    {
        return [
            $item->title,
            $item->status,
        ];
    }


    public function headings(): array
    {
        return [
            '标题',
            '状态',
        ];
    }
}

 3,180 total views,  2 views today

Revisions

There are no revisions for this post.

Comments are closed.