Laravel-excel: Start row (2) is beyond highest row (1)

Created on 12 Nov 2018  ·  25Comments  ·  Source: Maatwebsite/Laravel-Excel

Versions

PHP version: 7.2
Laravel version: 5.7
Package version: 3.1

Description

I'm getting the error: 'Start row (2) is beyond highest row (1)' from /Users/administrator/Sites/blog/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/RowIterator.php

The spreadsheet has headers on first row and is a single sheet. The second row is blank but shouldn't this be okay? I'm not sure how to account for this scenario. Any help is appreciated. Thank you.

App\Imports\PoliciesImport.php

<?php

namespace App\Imports;

use App\Policy;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithValidation;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\WithMultipleSheets;
use Auth;


class PoliciesImport implements ToModel, WithValidation, WithHeadingRow, WithMultipleSheets
{

    use Importable;

    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function model(array $row)
    {
        return new Policy([
          'user_id'     => Auth::user()->id,
          'policy_name' => $row['name'],
          'phone'       => $row['phone'],
          'street'      => $row['address'],
          'city'        => $row['city'],
          'state'       => $row['state'],
          'postal_code' => $row['postal_code'],
        ]);
    }

    public function sheets(): array
    {
        return [
            // Select by sheet index
            0 => new PoliciesImport(),
        ];
    }

    public function rules(): array
    {
        return [
            'policy_name' => 'required|string',
             '*.policy_name' => 'required|string',
        ];
    }

}

PolicyController.php

public function import(Request $request)
  {
    if ($request->hasFile('file')) {

      // validate incoming request
      $this->validate($request, [
        'file' => 'required|file|mimes:xls,xlsx,csv|max:10240', //max 10Mb
      ]);

          if ($request->file('file')->isValid()) {

              $file = $request->file('file');
              $path = $file->store('uploads/policy');
              $fileHeaders = current((new HeadingRowImport)->toArray($path)[0]);
              $validHeaders = [
                'name','phone','address','state','city','postal_code'
              ];
              sort($fileHeaders);
              sort($validHeaders);

              // Check the File Headers
              if ($fileHeaders == $validHeaders) {
                  // Import the saved excel file
                  (new PoliciesImport)->import($path);
              }

              Storage::delete($path);
          }
      }

      return back();

  }

Most helpful comment

i have same error !

but after remove sheet 2 , 3 solved !!

for this situation you need define sheet index by

    public function sheets(): array
    {
        return [
            // Select by sheet index
            0 => new pricelist_items(),
        ];
    }

All 25 comments

Can you post the full stacktrace? It's hard to see now which import causes it.

screen shot 2018-11-12 at 8 02 38 am 2

/Users/administrator/Sites/blog/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/RowIterator.php

     *
     * @param int $startRow The row number at which to start iterating
     *
     * @throws PhpSpreadsheetException
     *
     * @return RowIterator
     */
    public function resetStart($startRow = 1)
    {
        if ($startRow > $this->subject->getHighestRow()) {
            throw new PhpSpreadsheetException("Start row ({$startRow}) is beyond highest row ({$this->subject->getHighestRow()})");
        }

        $this->startRow = $startRow;
        if ($this->endRow < $this->startRow) {
            $this->endRow = $this->startRow;
        }
        $this->seek($startRow);

        return $this;
    }

    /**
     * (Re)Set the end row.
     *

Sorry about that. Does this help?

Thanks!

Having the same problem here!

According to the stacktrace your file only has 1 row (the heading row), when trying to import each row, PhpSpreadsheet complains that there's no 2nd row (and no rows further than the 2nd row)

@patrickbrouwers For my case, there definitely are rows and values beyond row 1. It seems that I have to ensure I implemented BOTH of the concerns WithChunkReading and WithCustomChunkSize to get passed the issue. Having said that, I also created a new Excel file and copied across the old file values.

Sounds like there might have been something wrong with your file, if it works after copying the values to a new file.
In case it's a CSV, perhaps not using the right delimiter?

Yeah. Quite possible. I will revert back here if it pops up again as I'll be processing a few different files soon. They are all XLSX files.

Sure, let me know!

@patrickbrouwers yes this is true. I'm trying to prevent a server error in this case, and I'm struggling how to catch it and stop the import model method from executing.

Am I on the right track by using RegistersEventListeners in App\Imports\PoliciesImport.php? I figured out how to get the highest row but I can't figure out how to pass this value or where to go from here.

    public static function beforeImport(BeforeImport $event)
    {
        $worksheet = $event->reader->getActiveSheet();
        $highestRow = $worksheet->getHighestRow(); // e.g. 10

        dd($highestRow);
    }

@abbylovesdon best is to throw an exception in beforeImport and try-catch it in the controller. You can pass the highest row through the exception.

@patrickbrouwers Thank you so much for your help! I'm new to PHP/Laravel/This Package so if anyone else is in my shoes here is what I did:

In my Import Class: App\Imports\PoliciesImport.php

<?php

namespace App\Imports;

use App\Policy;
use Auth;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Validators\Failure;
use Maatwebsite\Excel\Validators\ValidationException;
use Maatwebsite\Excel\Concerns\WithValidation;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Concerns\RegistersEventListeners;
use Maatwebsite\Excel\Events\BeforeImport;
use Maatwebsite\Excel\Concerns\WithMultipleSheets;

class PoliciesImport implements ToModel, WithValidation, WithHeadingRow, WithMultipleSheets, WithEvents
{
    use Importable, RegistersEventListeners;

    public static function beforeImport(BeforeImport $event)
    {
        $worksheet = $event->reader->getActiveSheet();
        $highestRow = $worksheet->getHighestRow(); // e.g. 10

        if ($highestRow < 2) {
            $error = \Illuminate\Validation\ValidationException::withMessages([]);
            $failure = new Failure(1, 'rows', [0 => 'Now enough rows!']);
            $failures = [0 => $failure];
            throw new ValidationException($error, $failures);
        }
    }

    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function model(array $row)
    {
        return new Policy([
          'user_id'     => Auth::user()->id,
          'policy_name' => $row['name'],
          'phone'       => $row['phone'],
          'street'      => $row['address'],
          'city'        => $row['city'],
          'state'       => $row['state'],
          'postal_code' => $row['postal_code'],
        ]);
    }

    public function sheets(): array
    {
        return [
            // Select by sheet index
            0 => new PoliciesImport(),
        ];
    }

    public function rules(): array
    {
        return [
            'name' => 'required|string',
             '*.name' => 'required|string',
        ];
    }

}

Now in my controller I can use:

                  try {
                        (new PoliciesImport)->import($path);
                  } catch (\Exception $e) {
                        $failures = $e->failures();
                        dd($failures[0]);
                  }

Having the same problem here! :((

Having the same problem here! :((

In case you're not able to fix the issue using the suggestions and examples above, I'd request you to open a new issue for it, using the issue template. Thanks!

i have same error !

but after remove sheet 2 , 3 solved !!

for this situation you need define sheet index by

    public function sheets(): array
    {
        return [
            // Select by sheet index
            0 => new pricelist_items(),
        ];
    }

Same case happened to me, but I realized that it's cause by multiple sheets existed in an excel file

I just had the same issue. After some frustration, my underlying suspicion proved true. It was being caused by a split in the spreadsheet. After 'unspliting' the first row it worked.
image

According to the stacktrace your file only has 1 row (the heading row), when trying to import each row, PhpSpreadsheet complains that there's no 2nd row (and no rows further than the 2nd row)

How to handle if excel have only header row. i want to show proper error message to client

Hello I know this thread is closed alrdy but I'm having the same issue here and nothing in this thread help with my problem.

I'm uploading 10k rows at the same time and I got this error Start row (2) is beyond highest row (1). But when I split it into 5k, it works like magic.

What seems to be the problem here?
Thanks in advance!

Hello I know this thread is closed alrdy but I'm having the same issue here and nothing in this thread help with my problem.

I'm uploading 10k rows at the same time and I got this error Start row (2) is beyond highest row (1). But when I split it into 5k, it works like magic.

What seems to be the problem here?
Thanks in advance!

Perhaps an error in the original file which you resolve by splitting it. It could be a performance issue as well, but hard to tell without seeing your code and your server specs. I'd guess it's a file error.

Just had this happen to me. Happens when the file is larger than PHP's 'upload_max_filesize' directive. I used chunking of 500 for a filesize of 5mb with 40k rows, while my maximum 'upload_max_filesize' on AWS AMI was 2MB. May I suggest to authors to implement checking for max upload size, and print this error instead of confusing Start row (2) is beyond highest row (1). When I increased the 'upload_max_filesize' limit the error was gone and file upload a success.

There’s most likely more reasons why phpspreadsheet may throw that error. You can always attempt a PR over there.

@GlennM thanks for the reply!
I have made a workaround for it and it alrdy suits the needs for my project for now. Will look upon your suggestion if I had this problem in the future.

@patrickbrouwers For my case, there definitely are rows and values beyond row 1. It seems that I have to ensure I implemented BOTH of the concerns WithChunkReading and WithCustomChunkSize to get passed the issue. Having said that, I also created a new Excel file and copied across the old file values.

it helps for me. still got same problem

delete worksheets are empty

delete worksheets are empty

This was my case, if you file has empty worksheets and you use "WithHeadingRow" this issue appears.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

rossjcooper picture rossjcooper  ·  3Comments

dr3ads picture dr3ads  ·  3Comments

amine8ghandi8amine picture amine8ghandi8amine  ·  3Comments

kurianic picture kurianic  ·  3Comments

vandolphreyes picture vandolphreyes  ·  3Comments