laravel excel3.1導出和導入

 

官方地址:https://docs.laravel-excel.com/3.1/getting-started/

一、導出

1.執行命令php artisan make:export ResourceViewLogExport --model=ViewLog 創建一個導出類

實現FromCollection接口類的collection()方法取數據

實現WithMapping接口類的map()方法格式化數據

實現WithHeadings接口類的headings()方法設置每列標題說明

實現WithTitle接口類的title()方法設置工作薄名字

<?php

namespace App\Exports;

use App\Models\ViewLog;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithTitle;

class ResourceViewLogExport implements FromCollection, WithMapping, WithHeadings,WithTitle
{
    public function __construct($start_time, $end_time)
    {
        $this->start_time = $start_time;
        $this->end_time = $end_time;
    }

    /**
     * @return \Illuminate\Support\Collection
	 *取數據
     */
    public function collection()
    {
        return ViewLog::viewLog(ViewLog::DOCTOR)->time($this->start_time, $this->end_time)
            ->unionAll(
                ViewLog::viewLog(ViewLog::STAFF)
                    ->time($this->start_time, $this->end_time)
            )->get();
    }

	//每列頭部標題
    public function headings(): array
    {
        return ['姓名', '用戶類型', '文章標題', '客戶端', '創建時間'];
    }
    //工作薄的名字
    public function title(): string
    {
        return '工作薄名字';
    }

	//遍歷數據,格式化數據進行輸出
    public function map($row): array
    {
        return [
            $row->user_name,
            $row->type == ViewLog::VIP ? 'VIP用戶' : '普通用戶',
            $row->title,
            $row->user_agent,
            $row->created_at,
        ];
    }
}

2.在控制器中調用導出類

通過download()方法進行導出

 

<?php

namespace App\Admin\Controllers;

use App\Exports\ResourceViewLogExport;
use App\Http\Controllers\Controller;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;

class ExportData extends Controller
{
    protected $start_time = 7;
    protected $end_time = 23;

    //導出文章閱讀記錄
    public function exportResourceViewLog(Request $request)
    {
        set_time_limit(0);
        $start_time = Carbon::parse($request->get('start_time'));
        $end_time = Carbon::parse($request->get('end_time'))->addDays(1);
        $filename = '文章閱讀明細_' . date('Y-m-d') . '.xlsx';
        return Excel::download(new ResourceViewLogExport($start_time, $end_time), $filename);
    }

}


二、導入

1.執行php artisan admin:import InfoImport --model=Models\Info命令創建一個導入類

<?php

namespace App\Imports;

use App\Models\Info;
use Maatwebsite\Excel\Concerns\ToModel;

class InfoImport implements ToModel
{
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function model(array $row)
    {
        return new Info([
            //
        ]);
    }
}

對於簡單的導出,使用model()的方式(因爲無法進行復雜的判斷,比如導入的時候判斷數據是否已存在等,也可能是我不會用此方式,歡迎留言指教

我一般的處理方式都是Excel::toArray()的方式

2.在控制器裏通過Excel::toArray()進行導入

<?php

namespace App\Http\Controllers;

use App\Models\Info;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;

class InfoImportController extends Controller
{

    public function index(Request $request)
    {
        set_time_limit(0);
        $oFile = $request->file('file');
        if (empty($oFile)) {
            return json_encode(['success'=>false,'msg'=>'請選擇文件']);
        }
        if ($oFile->isValid()) {
            $sExtName = $oFile->getClientOriginalExtension();
            $sExt = strtolower($sExtName);
            if (!in_array($sExt, ['xls', 'csv', 'xlsx'])) {
                return json_encode(['success'=>false,'msg'=>'應上傳正確格式的文件']);
            }
            $aContest = Excel::toArray(new \App\Imports\InfoImport(), $oFile);
            return $this->dealTableData($aContest);
        } else {
            return json_encode(['success'=>false,'msg'=>'您選上傳文件無效']);
        }
    }
    public function dealTableData($aWorkSheet)
    {
        //去掉首行每列的標題
        unset($aWorkSheet[0][0]);
        foreach ($aWorkSheet[0] as $k => $v) {
            if ($v) {
                //編輯excel時,如果只是清空內容,沒有刪除之前增加過的行,會有很多空的行
                if (!$v[0]) {
                    continue;
                }
                //處理髮布時間字段,因爲上傳的時候,會將時間轉成正整數,所以需要再轉成時間格式 如:2109-12-16
                $time = gmdate('Y-m-d', intval(($v[5] - 25569) * 3600 * 24));
                $aInfos[$k] = array(
                    'title' => $v[1],
                    'content' => $v[2],
                    'author' => $v[3],
                    'type' => $v[4],
                    'publish_time' => $time,
                    'created_at' => Carbon::now(),
                    'updated_at' => Carbon::now()
                );
            }
            if (empty($aInfos[$k]['title']) || empty($aInfos[$k]['content']) || empty($aInfos[$k]['author']) || empty($aInfos[$k]['type'])) {
                return json_encode(['success'=>false,'msg'=>'表格保存失敗,第' . $k . '條信息不全!']);
            } else {
                $oInfo = Info::where('title',$aInfos[$k]['title'])->first();
                if ($oInfo) {
                    return json_encode(['success'=>false,'msg'=>'每個標題只能有一個,第' . $k . '條標題重複!']);
                }
            }
        }
        $flag = Info::insert($aInfos);
        if (!$flag) {
            return json_encode(['success'=>false,'msg'=>'數據插入失敗']);
        }
        return json_encode(['success'=>true,'msg'=>'批量數據保存成功']);
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章