简体   繁体   English

laravel excel读取文件而不导入数据库

[英]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/ )我正在使用这个库来管理 laravel 项目上的 excel 文件( 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.一旦我从本地上传并作为 JSON 返回,我想只读 excel 文件。

My code in controller is我在控制器中的代码是

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

where ProductsImport file is ProductsImport 文件在哪里

<?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. $theArray 包含“myexcelfile.xlsx”文件的内容。 in order to skip adding the content of the excel file to the database you can use [] instead of the ProductsImport object.为了跳过将 excel 文件的内容添加到数据库中,您可以使用 [] 而不是 ProductsImport 对象。

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.以下是一些基于使用常用文件输入导入 csv 文件的工作示例。 In my case, once uploaded the file is accessible through the request object as 'csv_file'.就我而言,一旦上传文件,就可以通过请求对象作为“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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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