简体   繁体   中英

laravel excel read file without import to database

I'm using this libray to manage excel file on laravel project ( https://docs.laravel-excel.com/3.1/getting-started/ )

I would like to readonly excel file once I upload in from local and return as JSON.

My code in controller is

$excel = $request->file('excel');
$array = Excel::import(new ProductsImport, $excel);

where ProductsImport file is

<?php

namespace App\Imports;

use App\Models\Product;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\ToModel;

class ProductsImport implements ToModel
{

    use Importable;

    /**
     * @param array $row
     *
     * @return Products|null
     */
    public function model(array $row)
    {

        //return $row;

        return new Product([
            'name' => $row[0],
            'email' => $row[1]
        ]);

    }
}

you can try this solution:

$theArray = Excel::toArray([], 'myexcelfile.xlsx');

$theArray contains the content of the 'myexcelfile.xlsx' file. in order to skip adding the content of the excel file to the database you can use [] instead of the ProductsImport object.

Thx to Hadi for pointing us in the right direction. Here are some working examples based on importing a csv file using the usual file input. In my case, once uploaded the file is accessible through the request object as 'csv_file'.

public function importCSV(Request $request)
{
    // Get the csv rows as an array
    $theArray = Excel::toArray(new stdClass(), $request->file('csv_file'));

    // Get the csv rows as a collection
    $theCollection = Excel::toCollection(collect([]), $request->file('csv_file'));

    //etc
}

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