简体   繁体   English

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

[英]Laravel : How to Import Excel file to Database

I want to import some data through Excel file to Database. 我想通过Excel文件将一些数据导入数据库。 But while uploading Noting get uploaded in Database. 但是在上传时,Noting将在数据库中上传。

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 : 我想上传如下图所示的文件: 在此处输入图片说明

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');
        }
    }
}

I think whats missing is this enctype="multipart/form-data" in your form. 我认为您的表单中缺少此enctype =“ multipart / form-data”。 Hope it helps 希望能帮助到你

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库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM