我正在使用此libray来管理laravel项目(https://docs.laravel-excel.com/3.1/getting-started/)上的excel文件
从本地上传并以JSON格式返回后,我想只读excel文件。
我在控制器中的代码是
$excel = $request->file('excel');
$array = Excel::import(new ProductsImport, $excel);
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]
]);
}
}
答案 0 :(得分:3)
您可以尝试以下解决方案:
$theArray = Excel::toArray([], 'myexcelfile.xlsx');
$ theArray包含“ myexcelfile.xlsx”文件的内容。 为了跳过将excel文件的内容添加到数据库中,可以使用[]代替ProductsImport对象。
答案 1 :(得分:1)
感谢哈迪为我们指明了正确的方向。 以下是一些基于使用常用文件输入导入 csv 文件的工作示例。就我而言,一旦上传文件,就可以通过请求对象作为“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
}