【问题标题】:How do I import specific columns from XLSX to an array (Laravel)?如何将特定列从 XLSX 导入数组(Laravel)?
【发布时间】:2021-04-05 15:42:06
【问题描述】:

我需要将一个表导入到一个数组中。并且不是导入所有单元格,而是仅导入 2 列。

例如,来自

A B C D F
1 2 3 4 5
6 7 8 9 10

[
    {
        'A' => 1,
        'F' => 5,
    },
    {
        'A' => 6,
        'F' => 10,
    }
]

app\Imports\PricesImport.php

<?php

namespace App\Imports;

use Maatwebsite\Excel\Concerns\ToArray;
use Maatwebsite\Excel\Concerns\Importable;

class PricesImport implements ToArray
{
    use Importable;

    public function array(array $rows)
    {
        return array($rows[0], $rows[4]);
    }
}

以及控制器中的调用:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Imports\PricesImport;
use Maatwebsite\Excel\Facades\Excel;

class SomeController extends Controller
{
    public function import(Request $request) {
        $array = Excel::toArray(new PricesImport, $request->file('file'));
    }
}

但它不起作用。我做错了什么?

更新

尝试了此选项,但它返回所有列,而不是 2 个特定列 app\Imports\PricesImport.php

<?php

namespace App\Imports;

use Maatwebsite\Excel\Concerns\ToArray;
use Maatwebsite\Excel\Concerns\Importable;

class PricesImport implements ToArray
{
    use Importable;
    private $data;

    public function __construct()
    {
        $this->data = [];
    }

    public function array(array $rows)
    {
        foreach ($rows as $row) {
            $row = $row->toArray();
            $this->data[] = array('sku' => $row[0], 'price' => $row[4]);
        }
        return $this->data;
    }
}

【问题讨论】:

    标签: laravel maatwebsite-excel


    【解决方案1】:

    感谢Patrick Brouwers 的提示,这成功了: app\Imports\PricesImport.php

    <?php
    
    namespace App\Imports;
    
    use Maatwebsite\Excel\Concerns\ToArray;
    
    class PricesImport implements ToArray
    {
        private $data;
    
        public function __construct()
        {
            $this->data = [];
        }
        public function array(array $rows)
        {
            foreach ($rows as $row) {
                $this->data[] = array('sku' => $row[0], 'price' => $row[4]);
            }
        }
    
        public function getArray(): array
        {
            return $this->data;
        }
    }
    

    以及控制器中的调用:

    <?php
    
    namespace App\Http\Controllers;
    
    use Illuminate\Http\Request;
    use App\Imports\PricesImport;
    use Maatwebsite\Excel\Facades\Excel;
    
    class SomeController extends Controller
    {
        public function import(Request $request) {
            $import = new PricesImport;
            Excel::import($import, $request->file('file'));
            $array = $import->getArray();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-12-30
      • 1970-01-01
      • 2020-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-06
      • 1970-01-01
      • 2012-04-17
      相关资源
      最近更新 更多