Laravel-excel: [QUESTION] programmatically set the row of the heading row

Created on 30 Oct 2020  路  4Comments  路  Source: Maatwebsite/Laravel-Excel

Prerequisites

Versions

  • PHP version: 7.4.9
  • Laravel version: 8.11.2
  • Package version: 3.1

Description


Is there a way to set the row of the heading beforehand? Let's say I have two Excel files, one has the heading on row 1, on hast the heading on row 25. How do I set the heading row when instantiating (new ExcelImport)->toCollection('filename.xlsx')? Using the class constructor and passing in the desired value does not work as expected.

question

Most helpful comment

public function sheets(): array
    {
        return [
            new self,
        ];
    }

You are not passing the heading row there

All 4 comments

Pass the heading row via the constructor, put it in a property and return the value in the headingRow method https://docs.laravel-excel.com/3.1/imports/heading-row.html#heading-row-on-different-row

I've tried that:

(new ContactImport(25))->toCollection($file);
<?php

namespace App\Imports;

use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithCalculatedFormulas;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithMultipleSheets;
use Maatwebsite\Excel\Imports\HeadingRowFormatter;

HeadingRowFormatter::default('none');

class ContactImport implements ToCollection, WithHeadingRow, WithCalculatedFormulas, WithMultipleSheets
{
    use Importable;
    protected $headingRowNumber;

    public function __construct($headingRowNumber)
    {
        $this->headingRowNumber = $headingRowNumber;
    }

    public function sheets(): array
    {
        return [
            new self,
        ];
    }

    public function collection(Collection $collection)
    {
    }

    public function headingRow(): int
    {
        return $this->headingRowNumber;
    }
}

This throws Too few arguments to function App\Imports\ContactImport::__construct(), 0 passed and exactly 1 expected

When I dd($headingRowNumber) in the class constructor, I can see the value being passed.

public function sheets(): array
    {
        return [
            new self,
        ];
    }

You are not passing the heading row there

public function sheets(): array
    {
        return [
            new self,
        ];
    }

You are not passing the heading row there

Dude, I've just facepalmed myself into a coma. Of course, you're right, sorry for taking up your time - THANKS!!!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

alejandri picture alejandri  路  3Comments

matthewslouismarie picture matthewslouismarie  路  3Comments

dr3ads picture dr3ads  路  3Comments

kurianic picture kurianic  路  3Comments

rossjcooper picture rossjcooper  路  3Comments