laravel maatwebsite/excel 简单使用-导入

 之前写过关于maatwebsite/excel导出的简单用法,今天来看下导入的使用

<?php

namespace App\Http\Controllers\Example;

use App\Http\Controllers\Controller;
use App\Services\ImportService;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Maatwebsite\Excel\Facades\Excel;

class ExampleController extends Controller {

    /**
     * 导入excel数据
     * @param Request $request
     * @return JsonResponse
     */
    public function importExcel (Request $request): JsonResponse {
        $file = $request->file('file');
        $type = $request->input('type');
        Excel::import(new ImportService($type), $file);
        return $this->success(true);
    }
}

 我这里使用的是array,同时maatwebsite/excel还支持(ToCollection)集合,(ToModel)model这两种方式导入

<?php


namespace App\Services;

use Carbon\Carbon;
use Illuminate\Support\Str;
use Maatwebsite\Excel\Concerns\ToArray;

class ImportService implements ToArray {

    public $type;

    public function __construct (string $type = '') {
        $this->type = $type;
    }

    public function array (array $array): void {
        switch ($this->type) {
            case 'pay':
                break;
            case 'gm':
                break;
            case 'create':
                break;
            case 'active':
                break;
            default:
                $this->handleData($array);
                // dd( Carbon::parse('1970-01-01')->addDays(44707-25569)->toDateTimeString());
                // 结果 2022-05-26 00:00:00
                break;
        }
    }

    public function handleData (array $array) {
        // 去除表头
        unset($array[0]);
        $dateTime = Carbon::now()->toDateTimeString();
        collect($array)->chunk(1000)->map(function ($value) use ($dateTime) {
            $insertData = collect($value)->map(function ($val) use ($dateTime) {
                return [
                    'date'       => Carbon::parse('1970-01-01')->addDays($val[0]-25569)->toDateTimeString(),
                    'name'       => $val[1],
                    'status'     => $val[2],
                    'created_at' => $dateTime,
                    'updated_at' => $dateTime,
                ];
            })->toArray();
            // 插入数据
        });
    }

}

 这里的时间需要单独处理,excel使用的时间是格林威治时间,所以我们在使用excel导入时间的时候需要特别注意,时间会被转为从1900-01-01日开始计算的天数,而EXCEL中1970-01-01天数为25569,所以我们在计算excel中的时间的时候应该先减去25569天

以上就是导入的全部过程, 希望对大家有所帮助

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值