How to get excel to array in maatwebsite

2019-05-14 17:38发布

I am trying to convert an Excel file to an array using the latest version of Laravel-Excel (3.1.9)

The code below will download the file:

return Excel::download(new SalesOrderExport('columns'),'test.xlsx')

But I need to convert it to get an array only. I don't want to store this Excel data in a database at this point.

I tried with the code below but it did not work as the load method is not available in version 3.

Excel::load($request->file('sampledata'), function ($reader) {
    return response()->json($reader);
});

Please share your thoughts on how to get an array from Excel.

4条回答
做个烂人
2楼-- · 2019-05-14 17:49

Here is how I achieved this:

In my UsersImport class: namespace App\Imports;

use App\User;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\Importable;

class UsersImport implements ToModel
{
    use Importable;

    public function model(array $row)
    {
        return new User([
           'id' => $row[0]
        ]);
    }
}

And in controller:

$imported_users = (new UsersImport)->toArray(request()->file('excel_file'))[0];

I hope it helps you.

查看更多
淡お忘
3楼-- · 2019-05-14 17:53

You should try this:

$data = Excel::load($request->file('sampledata'), function ($reader) use($table) {
        $data = $reader->toArray();
        //here data has all excel data in array.
});
查看更多
戒情不戒烟
4楼-- · 2019-05-14 18:00

1) Create Import File using below command.

php artisan make:import TestImport

2) Inside TestImport make changes like this:

namespace App\Imports;

use App\User;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;

class TestImport implements ToCollection
{
    public function collection(Collection $rows)
    {
        return $rows;
    }
}

3) In Controller make changes like this:

 $rows = Excel::import(new TestImport, 'test.xlsx');
查看更多
成全新的幸福
5楼-- · 2019-05-14 18:01

I and @narayan tried hard to make requested excel file into array. Now I am able to get array properly with below code

$rows = Excel::toArray(new SalesOrderImport, $request->file('sampledata')); 

In my SalesOrderExport class I have default function only, which is required as abstract method.

namespace App\Exports;

use App\SalesOrder;
use Maatwebsite\Excel\Concerns\FromCollection;

class SalesOrderExport implements FromCollection
{
    public function collection()
    {   
        return SalesOrder::all();
    }
}

My Controller code

public function importTest(Request $request)
{
    $rows = Excel::toArray(new SalesOrderImport, $request->file('sampledata'));
    return response()->json(["rows"=>$rows]);
}

And in HTML

<input class="" type="file" name="sampledata" id="sampledata">

I already created this export by

php artisan make:import SalesOrder

Attaching related images

enter image description hereenter image description here

查看更多
登录 后发表回答