28

I have this project where I should be able to upload an excel file and read the contents then upload the information to the database. So I decided to use a library to help me out which turns to be Maatwebsite/Laravel-Excel

But I tried reading the documentation http://www.maatwebsite.nl/laravel-excel/docs/import but I can't seem to find the one that I need.

For example in my excel file in the first row John, Kennedy, Male which in my database corrensponds First Name, Last Name, Gender. How can I read it and upload? Can someone help me?

Thanks!

My code as of now

public function postUploadCsv()
{
    $rules = array(
        'file' => 'required',
        'num_records' => 'required',
    );

    $validator = Validator::make(Input::all(), $rules);
    // process the form
    if ($validator->fails()) 
    {
        return Redirect::to('customer-upload')->withErrors($validator);
    }
    else 
    {
        $file = Input::file('file');
        dd($file);
        exit();
    } 
}
jackhammer013
  • 2,295
  • 11
  • 45
  • 95

2 Answers2

57

given your excel sheet column names are exactly as database column names following is suffice,

add following above controller class,

use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Support\Facades\Input;

and function code,

public function postUploadCsv()
{
    $rules = array(
        'file' => 'required',
        'num_records' => 'required',
    );

    $validator = Validator::make(Input::all(), $rules);
    // process the form
    if ($validator->fails()) 
    {
        return Redirect::to('customer-upload')->withErrors($validator);
    }
    else 
    {
        try {
            Excel::load(Input::file('file'), function ($reader) {

                foreach ($reader->toArray() as $row) {
                    User::firstOrCreate($row);
                }
            });
            \Session::flash('success', 'Users uploaded successfully.');
            return redirect(route('users.index'));
        } catch (\Exception $e) {
            \Session::flash('error', $e->getMessage());
            return redirect(route('users.index'));
        }
    } 
} 

UPDATE

Suppose you have more than one sheet in a workbook, you will have additional foreach to iterate over sheets as below,

Excel::load(Input::file('file'), function ($reader) {

     $reader->each(function($sheet) {    
         foreach ($sheet->toArray() as $row) {
            User::firstOrCreate($row);
         }
     });
});

Read More

In case you are using Laravel 5.3 and given that your excel sheet columns are not exact

Make use of the following code to suite your needs

/**
 * Import file into database Code
 *
 * @var array
 */
public function importExcel(Request $request)
{
    if($request->hasFile('import_file')){

        $path = $request->file('import_file')->getRealPath();
        $data = Excel::load($path, function($reader) {})->get();

        if(!empty($data) && $data->count()){

            foreach ($data->toArray() as $key => $value) {

                if(!empty($value)){

                    foreach ($value as $v) {        

                        $insert[] = ['title' => $v['title'], 'description' => $v['description']];

                    }
                }
            }

            if(!empty($insert)){
                Item::insert($insert);
                return back()->with('success','Insert Record successfully.');
            }
        }
    }

    return back()->with('error','Please Check your file, Something is wrong there.');

}

Check out the full tutorial here

Note that by default - Once your data is extacted from you excel sheet, all the column names are converted to lower case, and all spaces between the names are replaced with underscore.

kjones
  • 1,339
  • 1
  • 13
  • 28
pinkal vansia
  • 10,240
  • 5
  • 49
  • 62
  • 1
    Hi. Thanks for the help, I've already fixed my problem before I saw your answer but your User::firstOrCreate($row); helped me to have a cleaner code. than to assign each value like $customer->title = $value['title']; Thanks! I'll accept this :) – jackhammer013 Jul 13 '15 at 09:06
  • 1
    @pinkalvansia what if there are 2 or more sheets ? Because, according to your code, `foreach` will take only first sheet, Right ? – Saiyan Prince Jul 16 '15 at 10:05
  • 1
    @pinkalvansia Thank you so much. But I only have 1 sheet so it's ok, but thanks anyway, I could reference to this in the future. – jackhammer013 Jul 17 '15 at 13:16
  • 2
    I wish to know how do import excel into an existing table with existing records. Also the column names are as on the table though the excel sheet does not carry all the column names on the existing table. – The Oracle Dec 06 '16 at 19:44
  • what if there are 8000 rows? How do we use queue? – KD.S.T. Apr 24 '18 at 11:21
0

I have this project where I should be able to upload an excel file and read the contents then upload the information to the database. So I decided to use a library to help me out which turns to be

<?php

namespace App\Imports;

use App\Models\aas;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Concerns\ToCollection;


class Lecture implements ToCollection
{
    /**
    * @param Collection $collection
    */
    public function collection(Collection $collection)
    {
        $t=count($collection[0]);
        foreach ($collection as $row) 
        {
            
            for ($i=0; $i < $t; $i++) { 
                if ($i==0) {
                    $ver=mb_strstr( $row[$i], '2021' );
                    if($ver==FALSE) break;
                }
                if (!empty($row[$i])) {
                    
                    switch ($collection[0][$i]) {
                        case 'Ag':
                            
                           aas::create([
                                'ref' => $row[0],
                                'lect' => $row[$i],
                                'code' => 9,
                                ]);
                            break;
                        case 'Cu':
                           
                            aas::create([
                                'ref' => $row[0],
                                'lect' => $row[$i],
                                'code' => 9,
                                ]);
                            
                            break;
                        case 'Pb':
                           
                            aas::create([
                                'ref' =>$row[0],
                                'lect' =>$row[$i],
                                'code' => 10,
                            ]);
                            break;
                        case 'Zn':
                           
                            aas::create([
                                'ref' =>$row[0],
                                'lect' =>$row[$i],
                                'code' => 11,
                            ]);
                            break;
                        case 'Mn':
                            
                            aas::create([
                                'reference_labo' =>$row[0],
                                'lecture' =>$row[$i],
                                'code' => 12,
                            ]);
                            break;
                        case 'Co':
                           
                            aas::create([
                                'ref' =>$row[0],
                                'lect' =>$row[$i],
                                'code' => 13,
                            ]);
                            break;
                        case 'Ni':
                            
                            aas::create([
                                'ref' =>$row[0],
                                'lect' =>$row[$i],
                                'code' => 14,
                            ]);
                            break;
                        case 'Fe':
                          
                            aas::create([
                                'ref' =>$row[0],
                                'lect' =>$row[$i],
                                'code' => 15,
                            ]);
                            break;
                    }
                  
                }
            }
        }
       
    }
}

my function executes well but the data does not register in the database

dot90
  • 1
  • This does not really answer the question. If you have a different question, you can ask it by clicking [Ask Question](https://stackoverflow.com/questions/ask). To get notified when this question gets new answers, you can [follow this question](https://meta.stackexchange.com/q/345661). Once you have enough [reputation](https://stackoverflow.com/help/whats-reputation), you can also [add a bounty](https://stackoverflow.com/help/privileges/set-bounties) to draw more attention to this question. - [From Review](/review/late-answers/30292136) – Ike Nov 09 '21 at 19:08