【问题标题】:how to import a transposed excel in Laravel using laravel-excel如何使用 laravel-excel 在 Laravel 中导入转置的 excel
【发布时间】:2021-07-05 18:07:35
【问题描述】:

我正在尝试将如下图所示的 excel 导入 Eloquent 模型:

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

【问题讨论】:

    标签: excel laravel laravel-excel


    【解决方案1】:

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

    我相信这里有两种选择:

    1. 将 Excel 工作表更改为基于行的布局
    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;
        }
    }
    

    您可以链接更多 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');
    });
    

    【讨论】:

    • rows 变量以以下格式返回数据:"city" =&gt; "population", "madrid" =&gt; 3.223, "milan" =&gt; 1.352, ...
    • 你到底是什么意思?您是否创建了一个单独的 Import 类来实现 ToCollection 接口? (见docs.laravel-excel.com/3.1/imports/collection.html)你回答后,我又试了一次。我使用您在.xlsx 文件中提供的完全相同的数据结构重新创建了您的问题。对我来说,该系列仅显示 3 个项目,如我之前的回答中所述。您能否提供完整的.xlsx
    • @ErwinSmith 我已经用一个工作示例更新了我的原始答案。你能告诉我这对你有用吗?如果没有,请提供您正在使用的完整的.xlsx;它可能与提供的示例不同。
    • 你说得对,我做了上面的 excel 来简化问题,我再次检查它,它可以工作,谢谢。
    猜你喜欢
    • 2020-07-09
    • 2019-03-10
    • 1970-01-01
    • 2021-04-26
    • 2021-10-08
    • 2019-03-12
    • 2018-05-20
    • 2019-07-23
    • 2021-03-10
    相关资源
    最近更新 更多