【发布时间】:2021-07-05 18:07:35
【问题描述】:
我正在尝试将如下图所示的 excel 导入 Eloquent 模型:
我在文档中没有找到直接的东西,我找到了这个解决方案 (https://docs.laravel-excel.com/3.1/imports/mapped-cells.html),但它只适用于 1 行数据。
【问题讨论】:
标签: excel laravel laravel-excel
我正在尝试将如下图所示的 excel 导入 Eloquent 模型:
我在文档中没有找到直接的东西,我找到了这个解决方案 (https://docs.laravel-excel.com/3.1/imports/mapped-cells.html),但它只适用于 1 行数据。
【问题讨论】:
标签: excel laravel laravel-excel
通读文档,我认为 Laravel Excel 包仅支持行形状的数据,开箱即用。
我相信这里有两种选择:
创建单独的导入
如果是后者,也许这样的事情会起作用。
<?php
// create file App/Imports/CitiesImport.php
namespace App\Imports;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
class CitiesImport implements ToCollection
{
public function collection(Collection $rows)
{
$transposedData = array_map(function (...$rows) {
return $rows;
}, ...$rows->values()->toArray());
$cities = collect($transposedData);
$headers = $cities->shift(); // The headers are the first entry of the collection, let's shift them for now
return $cities;
}
}
您可以链接更多 Collection 方法,例如 mapInto() (https://laravel.com/docs/8.x/collections#method-mapinto) 以将集合映射到模型集合。
上面的代码应该返回:
Illuminate\Support\Collection {#2006
#items: array:3 [
0 => array:3 [
0 => "Madrid"
1 => "3.233"
2 => "1"
]
1 => array:3 [
0 => "Milan"
1 => "1.352"
2 => "0"
]
2 => array:3 [
0 => "Paris"
1 => "2.161"
2 => "0"
]
]
}
我已经在本地重新创建了这个问题,并确认它使用测试路线工作。只需确保将您的 .xlsx 文件放在您的 /public 文件夹中或更改代码中的位置即可。
<?php
// in routes/web.php
use App\Imports\CitiesImport;
use Maatwebsite\Excel\Facades\Excel;
Route::get('/test/import', function() {
Excel::import(new CitiesImport(), 'test.xlsx');
});
【讨论】:
"city" => "population", "madrid" => 3.223, "milan" => 1.352, ...
ToCollection 接口? (见docs.laravel-excel.com/3.1/imports/collection.html)你回答后,我又试了一次。我使用您在.xlsx 文件中提供的完全相同的数据结构重新创建了您的问题。对我来说,该系列仅显示 3 个项目,如我之前的回答中所述。您能否提供完整的.xlsx?
.xlsx;它可能与提供的示例不同。