Import Excel Sheet in Laravel and show the extracted data in UI

908 Views Asked by At

I am using Angular 4 in my Front end and Laravel 5.2 in my backend.I want to import an Excel sheet from UI, store the values in DB, retrieve the values and show them in UI using Angular.

I am using Maatwebsite/Excel package in laravel for this. My excel sheet has the following structure.

Image Link

name | details | price
expertphp | Online Tutorials | 100
hello | code | 200

My laravel code is as below: Here myFile is the key which has the file path and name as its value.

    $File = $request->file('myFile');
    $path = $request->file('myFile')->getRealPath();
    $real_name = $File->getClientOriginalName();
    $data = Excel::load($path)->get();

    if($data->count()){
        foreach($data as $key => $value){
            $arr[] = ['name' => $value->name, 'details' => $value->details, 'price' => $value->price];
        }
    }

    return response()->success($data);

I get my reponse as below:

     {
        "errors":false,
        "data":[
                {
                   "namedetailsprice":"expertphp\tOnline tutorials\t100"
                },
                {
                   "namedetailsprice":"hello\tfirst code\t2000"
                }
               ]
      }

I am not understanding why is the headers becoming one field. Appreciate any help.

Thanks.

1

There are 1 best solutions below

8
On

I think if you change your code to this code it will work or it will get you closer to your solution:

$File = $request->file('myFile');
$path = $request->file('myFile')->getRealPath();
$real_name = $File->getClientOriginalName();
$data = Excel::load($path)->get();
$returnData = [];

if($data->count()){
    foreach($data as $key => $value){
        $arr = ['name' => $value->name, 'details' => $value->details, 'price' => $value->price];
        array_push($returnData,$arr);
    }
}

return response()->success($returnData);

If I understand you correctly, then you would want this new $returnData to be returned instead of the raw loaded excel file. One other reason that I changed your code was that you were saving only one row of your data and replacing it with another row in the same array $arr. Now it is pushing new rows every time and saving all.