简体   繁体   中英

Make the equivalent of pandas.read_csv(file) with Laravel Excel

I'm trying to read a.csv/.xlsx file using Laravel Excel in the same manner as you would do with the Python library pandas, with the function read_csv(), but instead of saving the file contents to a DataFrame I want them in a collection. So pretty much identify the first line as a header and name the other rows keys based on the header names.

Currently, I'm able to save each row to a collection with this import file and running the command:

$collection = \Excel::toCollection(new TestImport, file);
<?php

namespace App\Imports;

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

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

But this way the keys (header) is just saved as another item of the collection (a row). So far I've been able to come up with two possible solution that are not ideal:

1) Read the file fist just to get the headers, then pass them as an argument to the constructor of the import class and define the key name manually.

2) After reading the file, iterate over the collection naming all item keys.

Anyone knows a better and more straight forward way of doing this?

Ok, apparently all you need to do is to implement the WithHeadingRow concern, the code becomes like this:

<?php

namespace App\Imports;

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

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

This will return you a collection with keys set according to.csv file header.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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