begineeeerrrr
begineeeerrrr

Reputation: 343

Laravel excel, reading horizontally

Currently using Laravel-Excel (Maatwebsite) package for uploading excel and read them. Problem is, how to read horizontal and vertical data in a same excel file?

My excel file looks like this-

enter image description here

So far, this is my codes but it didnt read anything

$rows = Excel::load('storage\\app\\public\\upload\\Funiture.xlsx)->get();

@foreach ($rows as $key => $value)
    <tr>
      <td>{{ $value->{'Furniture Registration Number'} }}</td>
      <td>{{ $value->{'Number'} }}</td>
      <td>{{ $value->{'Chair Name'} }}</td>
      <td>{{ $value->{'Table Name'} }}</td>
      <td>{{ $value->{'Carpet Color'} }}</td>
   </tr>
@endforeach

EDIT

$rows = Excel::load('storage\\app\\public\\upload\\Funiture.xlsx)->get();
<span>Furniture Registration Number : <b>{{ $rows[0][1] }}</b></span>

$rows = Excel::load('storage\\app\\public\\upload\\Funiture.xlsx, function($reader){$reader->noHeading(); $reader->skipRows(3); })->get();;

@foreach ($rows as $key => $value)
  <tr>
    <td>{{ $value->[0] }}</td>
    <td>{{ $value->[1] }}</td>
    <td>{{ $value->[2] }}</td>
    <td>{{ $value->[3] }}</td>
  </tr>
@endforeach

Is it correct?

EDIT

enter image description here

This is result of dd(rows). How do I retrieve the amount of array? In this case, it have 7 as shown in the picture

Upvotes: 3

Views: 3105

Answers (1)

R.K.Saini
R.K.Saini

Reputation: 2708

As Laravel-Excel documentation says:

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

So you need to define proper heading for first row if you want to use attribute. Otherwise you can do one thing just egnore heading

Try this

   $rows= Excel::load("storage\\app\\public\\upload\\Funiture.xlsx", function($reader) {
       $reader->noHeading();
        $reader->skipRows(3); // skip first three rows as they contain headings
    })->get();
    $rows = $rows->toArray();

And then in your view you can loop through the rows like this

@foreach ($rows as $key => $value)
    <tr>
      <td>{{ $value[0] }}</td>
      <td>{{ $value[1] }}</td>
      <td>{{ $value[2] }}</td>
      <td>{{ $value[3] }}</td>
   </tr>
    @endforeach

EDIT :

You don't need to read file twice just read file without skipping 3 rows and then use array_slice to skip first 3 rows after reading value at index [0][1].

     $rows= Excel::load("storage\\app\\public\\upload\\Funiture.xlsx", function($reader) {
           $reader->noHeading();
     })->get();
   $rows = $rows->toArray();

Then in your view

<span>Furniture Registration Number : <b>{{ $rows[0][1] }}</b></span>
@php
    $rows = array_slice($rows,4);
@endphp

@foreach ($rows as $key => $value)
  <tr>
    <td>{{ $value->[0] }}</td>
    <td>{{ $value->[1] }}</td>
    <td>{{ $value->[2] }}</td>
    <td>{{ $value->[3] }}</td>
  </tr>
@endforeach

Upvotes: 3

Related Questions