기술나눔

Laravel : Excel 파일을 데이터베이스로 가져오는 방법

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

1. 전제

Excel 콘텐츠를 데이터베이스에 저장하려는 경우 laravel에는 일반적으로 사용할 수 있는 확장 기능이 있습니다.maatwebsite/excel, 설치 단계 참조이전 기사: laravel에 Maatwebsite/excel 확장 설치

2. 사용

2.1. 새로운 가져오기 파일을 생성합니다.

php artisan make:import 文件名称 --model=Model地址
  • 1

여기에 이미지 설명을 삽입하세요.

그런 다음 가져오기 논리를 내부에 작성하세요.

<?php

namespace AppImports;

use AppExceptionsApiException;
use IlluminateSupportFacadesDB;
use MaatwebsiteExcelConcernsToArray;
use MaatwebsiteExcelConcernsWithChunkReading;
use MaatwebsiteExcelConcernsWithHeadingRow;

class QuesExport implements ToArray, WithChunkReading, WithHeadingRow
{

    public function array(array $rows)
    {
        $data = [];
        $now = date('Y-m-d H:i:s');
        foreach ($rows as $row) {

            $data[] = [
                'id' => $row['id'],
                'number' => 0,
                'parent_id' => 0,
                'type' => 1,
                'question' => $row['ques'],
                'standard_answer' => $row['answer'],
                'ai_ques_id' => $row['aiid'],
                'created_at' => $now
            ];
        }

        if (!$data) {
            throw new ApiException('没有要导入的数据');
            return false;
        };

        //全部导入
        DB::select('TRUNCATE table questions_copy1');

        DB::table('questions_copy1')->insert($data);

        return true;
    }

    public function chunkSize(): int
    {
        return 500;
    }

    public function headingRow(): int
    {
        return 1;
    }

    /**
     * @param Failure[] $failures
     */
    public function onFailure(Failure ...$failures)
    {
        // Handle the failures how you'd like.
        throw new ApiException('fhwaeurewsdf');
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64

2.2. 새로운 컨트롤러와 메소드를 생성하고 가져오기 파일을 호출합니다.

    /**
     * 导入excel,入库
     *
     * */
    public function uploadQues(Request $request){
        $file = $request->file('file');

        // 保存上传文件
        $path = public_path('uploads/admin/ques');
        $this->mkdirs($path); // 已存在的路径不会再创建
        $fileName = date('YmdHis') . '_' . uniqid() . '_' . '.' . strtolower($file->getClientOriginalExtension());
        $file->move($path, $fileName);

        // 读取文件并入库
        Excel::import(new QuesExport(), $path . '/' . $fileName);

        // 删除上传文件
        unlink($path . '/' . $fileName);

        return response()->json([
            'status'=>1,
            'msg'=>'',
        ]);
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

2.3. 파일 업로드를 지원하는 새 페이지를 만듭니다.

나는 여기에 다음과 같이 간단히 페이지를 작성했습니다.

<!DOCTYPE html>
<html >
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Laravel</title>
    <script  src="/js/jquery-3.3.1.min.js?v=2021123999" type="text/javascript" charset="utf-8"></script>

    <meta name="csrf-token" content="{{ csrf_token() }}">
</head>
<body>
<div class="flex-center position-ref full-height">
    <div class="upload_box">
        <input type="file" name="file" accept="file" id="auth-upload"  onchange="uploadFile();"/>
        <div class="reload_file flex-v flex-vc flex-hc">
            <i class="icon icon_add"></i>
            <p>文件</p>
        </div>
    </div>
</div>

<script>

    function uploadFile(){
        file = $("#auth-upload")[0].files[0];

        // alert(file);
        // alert(file.name);
        // return;
        file_name = file.name;
        ext = file_name.slice(file_name.lastIndexOf(".")+1).toLowerCase();
        imgMaxSize = 1024*1024*10;
        if (ext != 'xlsx' ) {swal('文件格式不正确');return ;}
        // if (file.size > imgMaxSize) {swal('文件大小超过10M'); return ;}

        formData = new FormData();
        // 自定义formData中的内容
        formData.append('file', file);
        formData.append('_token', '{{csrf_token()}}');

        $.ajax({
            type: 'POST',
            url: "/upload",
            data: formData,
            cache: false,
            processData: false,
            contentType: false,
            dataType:'json',
            success: function (data) {
                if (data.status){
                  alert('成功');
                }else{
                    alert('失败');

                }
            }
        });
    }



</script>
</body>
</html>


  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67