0

I need to read an .xls file and put it into an array. I'm using laravel-excel package for reading excel files.

I have a Excel file like this :

enter image description here

I need to have an array like this :

[
 '9921234567' => 'First Text',
 '9929876544' => 'Second Text',
 '9927654321' => 'Third Text',
 '9928765432' => 'Fourth Text',

]

What I have tried so far :

 Excel::load('sample.xls', function($reader) {
     $reader->dd();
 });

Problem:

The problem is it reads the first row as column!

0 => RowCollection {#619
      #title: "Sheet1"
      #items: array:3 [
        0 => CellCollection {#623
          #title: null
          #items: array:2 [
            9921234567 => 9929876544.0
            "first_text" => "Second Text"
          ]
        }
        1 => CellCollection {#624
          #title: null
          #items: array:2 [
            9921234567 => 9927654321.0
            "first_text" => "Third Text"
          ]
        }
        2 => CellCollection {#625
          #title: null
          #items: array:2 [
            9921234567 => 9928765432.0
            "first_text" => "Fourth Text"
          ]
        }
      ]
    }

Look, I don't want to first row values count as column name!

Any helps would be great appreciated.

Hamed Kamrava
  • 12,359
  • 34
  • 87
  • 125

3 Answers3

6

You linked answer in documentation

Table heading as attributes By default the first row of the excel file will be used as attributes.

You can change the default inside the config excel::import.heading. Available options are: true|false|slugged|ascii|numeric|hashed|trans|original

I never used laravel but just set it to false and check what will happen.

Community
  • 1
  • 1
Vini
  • 627
  • 5
  • 18
1

The documentation says:

By default the first row of the Excel file will be used as attributes

So, I recommend to use noHeading function:

Excel::load('sample.xls', function($reader) {
     $reader->noHeading();
     $reader->dd();
 });
J.C. Gras
  • 4,934
  • 1
  • 37
  • 44
0

You need to loop thru each row. After that you can create your custom array when you loop thru all columns

Excel::load('sample.xls', function($reader) {
    $reader->each(function($sheet) {
        // Loop through all rows
        $sheet->each(function($row) {
            // Loop through all columns
        });
    });
})

This is just basic code for excel import, you need to adjust it to your example.

Hope it helps

KuKeC
  • 4,392
  • 5
  • 31
  • 60