如何使用 laravel-excel 在 Laravel 中导入转置的 excel

how to import a transposed excel in Laravel using laravel-excel

我正在尝试将看起来像下图的 excel 导入 Eloquent 模型:

我没有在文档中找到直接的内容,我找到了这个解决方案 (https://docs.laravel-excel.com/3.1/imports/mapped-cells.html),但它只适用于 1 行数据。

通读文档,我认为 Laravel Excel 包仅支持开箱即用的行形式的数据。

我相信这里有两个选择:

  1. 将您的 Excel sheet 更改为基于行的布局
  2. 创建您自己的导入器来转置数据(https://docs.laravel-excel.com/3.1/imports/collection.html)

创建单独的导入

如果是后者,也许这样的方法会起作用。

<?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;
    }
}

您可以链接更多集合方法,例如 mapInto() (https://laravel.com/docs/8.x/collections#method-mapinto),以将集合映射到模型集合中。

以上代码应该return:

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');
});