Obtaining and verifying headings in Laravel Excel 3.1

 Recently I came across a need to use Laravel Excel to determine if an imported file has specific headings before allowing the import. Its a lot easier than it sounds but the docs don't really help.


You have your headings in Excel 

col1, col2, col3 etc.


You have your expected headings

col1, col2, col4


What you need to do before importing the data from the file is get the headings out.


You can do this by using the HeadingRowImport class.

(new \Maatwebsite\Excel\HeadingRowImport)->toArray($filepath);

This is fine if that is all you are after but there are a few things to know.

First, there are multiple arrays returned using this method from a spreadsheet, I can only assume one of those arrays is sheet, as for the other?

Next, you CAN import from a different heading row than row 1 but you have to pass it in the constructor

(new \Maatwebsite\Excel\HeadingRowImport($rowOfHeadings))->toArray($filepath);


I wanted to verify specific headings existed in the supplied file so this is the code I ended up using the following. Note that this is using a single sheet on a single spreadsheet.

$headings = array_flip((new \Maatwebsite\Excel\HeadingRowImport($rowOfHeadings))->toArray($uploadPath)[0][0]);


foreach ($expectedHeadings as $expectedHeading) {

    if(!isset($headings[$expectedHeading])) {

        return false;

     }

}

return true; 

Comments