Laravel:如何将 Excel 文件导入数据库

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38802811/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 14:15:27  来源:igfitidea点击:

Laravel : How to Import Excel file to Database

phpexcellaravel

提问by Hola

I want to import some data through Excel file to Database. But while uploading Noting get uploaded in Database.

我想通过 Excel 文件将一些数据导入数据库。但是在上传注意时会上传到数据库中。

I'm not sure what's the wrong here, if anyone found out, hope help me to find it.

我不确定这里有什么问题,如果有人发现,希望能帮我找到它。

Here is my controller:

这是我的控制器:

 public function importExcel()
    {
        if(Input::hasFile('import_file')){
            $path = Input::file('import_file')->getRealPath();

            $data = Excel::load($path, function($reader){})->get()->toArray();
            if(!empty($data) && $data->count()){
                foreach ($data as $key => $value) {
                    $insert[] = ['title' => $value->title, 'description' => $value->description];
                }
                if(!empty($insert)){
                    DB::table('items')->insert($insert);
                //  dd('Insert Record successfully.');
                }
            }
        }
        return back();

        }

And here is the blade view:

这是刀片视图:

<html lang="en">
<head>
    <title>Import - Export Laravel 5</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" >
</head>
<body>
    <nav class="navbar navbar-default">
        <div class="container-fluid">
            <div class="navbar-header">
                <a class="navbar-brand" href="#">Import - Export in Excel and CSV Laravel 5</a>
            </div>
        </div>
    </nav>
    <div class="container">
        <a href="{{ URL::to('downloadExcel/xls') }}"><button class="btn btn-success">Download Excel xls</button></a>
        <a href="{{ URL::to('downloadExcel/xlsx') }}"><button class="btn btn-success">Download Excel xlsx</button></a>
        <a href="{{ URL::to('downloadExcel/csv') }}"><button class="btn btn-success">Download CSV</button></a>
        <form style="border: 4px solid #a1a1a1;margin-top: 15px;padding: 10px;" action="{{ URL::to('importExcel') }}" class="form-horizontal" method="post" >
            <input type="file" name="import_file" />
              {!! Form::token(); !!}
            {!!   csrf_field() ; !!} 
            <button class="btn btn-primary">Import File</button>
        </form>
    </div>
</body>
</html>

And I wanted to upload a file like below Image : enter image description here

我想上传一个像下图这样的文件: 在此处输入图片说明

回答by vaibhav raychura

please use : use Maatwebsite\Excel\Facades\Excel;

请使用:使用 Maatwebsite\Excel\Facades\Excel;

and make sure that name of excel column header is exact same to the database field name :

并确保 excel 列标题的名称与数据库字段名称完全相同:

public function importExcelDemo(Request $request)
{

    $rules = array(
        'import_file' => 'required'
    );

    $validator = Validator::make($request->all(), $rules);
    if ($validator->fails())
    {
        return Redirect::to('/home')->withErrors($validator);
    }
    else
    {
        try
        {
            Excel::load('C:/Users/EBIZ43/Downloads/'. $request['import_file'], function ($reader)
            {
                foreach ($reader->toArray() as $row)
                {
                    $data = $this->ads_repo->prepareData($row);
                    $result = $this->ads_repo->create($data);
                }
            });
            \Session::flash('success', 'Data imported successfully.');
            return redirect('/home');
        }
        catch (\Exception $e)
        {
            \Session::flash('error', $e->getMessage());
            return redirect('/home');
        }
    }
}

回答by Randall Anthony Bondoc

I think whats missing is this enctype="multipart/form-data" in your form. Hope it helps

我认为您的表单中缺少这个 enctype="multipart/form-data" 。希望能帮助到你

回答by Mina Abadir

In general, I see you tagged your question Laravel 5 while you are using obsolete Facades.

一般来说,我看到您在使用过时的 Facades 时标记了您的问题 Laravel 5。

I would recommend the following updates to your code:

我建议对您的代码进行以下更新:

public function importExcel(Request $request)
    {
        $file = $request->file('import_file')
        if($file){
            $path = $file->getRealPath();
            $data = Excel::load($path, function($reader) {
            })->get();
            if(!empty($data) && $data->count()){
                foreach ($data as $key => $value) {
                    $insert[] = ['title' => $value->title, 'description' => $value->description];
                }
                if(!empty($insert)){
                    DB::table('items')->insert($insert);
                //  dd('Insert Record successfully.');
                }
            }
        } 
    }

I would say, you have already installed the Excel library.

我会说,您已经安装了 Excel 库。