1
votes

I'm currently working on a Laravel project using the Laravel-Excel package.

It is working fine, except for a use case i'm trying to solve I'm trying to solve for a few hours now.

Each CSV files I'm reading begins with the Heading Rows, and that's particularly practical, but some of my CSV Files begin with annotations like #CSV DD V2.4.3 at row 1 followed by the Heading Rows at row 2.

So, I need to find out how to determine the real line where the heading rows are located to avoid that unwanted line. I especially need to make it work in the headingRow() method implemented by the WithHeadingRow interface. is there a way t grab lines from the csv file to determine the correct heading row line ?

Hope you'll find out , thanks in advance

1

1 Answers

0
votes

I would consider doing this in two steps. This is a very general example, so you will need to add in the appropriate Laravel Excel import concern and other dependencies, perform any checks to make sure the file exists, and so on.

  1. Check the first line of the file before starting the import to determine the correct heading row.
// get the first line of the file
$line = fgets(fopen('path/to/file.csv', 'r'));

// set the heading row based on the line contents
// add terms to search array if desired ['#CSV','...']
$heading_row = Str::startsWith(trim($line), ['#CSV']) ? 2 : 1;
  1. Dynamically inject the heading row value using the WithHeadingRow concern and associated method.
class SampleImport implements WithHeadingRow
{
    private $heading_row;

    // inject the desired heading row or default to first row
    public function __construct($heading_row = 1)
    {
        $this->heading_row = $heading_row;
    }

    // set the heading row
    public function headingRow(): int
    {
        return $this->heading_row;
    }    
}

Now you can pass a custom heading row when running the import.

Excel::import(new SampleImport($heading_row), 'path/to/file.csv');