How to read xls file in laravel - laravel-excel

S.M_Emamian picture S.M_Emamian · May 18, 2017 · Viewed 15k times · Source

I'm using laravel-excel library to read excel files.

http://www.maatwebsite.nl/laravel-excel/docs/import

   //http://localhost:8000/assets/panel/excel/test123.xls
    $address = URL::to('/assets/panel/excel/').'/test123.xls';
   // dd($address);
    Excel::load($address, function($reader) {

        $results = $reader->get();
        dd($results);

    });

this file http://localhost:8000/assets/panel/excel/test123.xls exist but I got this error:

Could not open C:\xampp\htdocs\tahrircenter\http://localhost:8000/assets/panel/excel/test123.xls for reading! File does not exist.

I know the meaning of the error, but how can I use my address instead of directory address in this library?

Answer

Dmytro Dzyubak picture Dmytro Dzyubak · May 19, 2017

Solution 1

Just tested and the following should work:

// /routes/web.php
Route::get('excel-test', function () {
    // http://localhost/assets/panel/excel/test123.xls
    // /public/assets/panel/excel/test123.xls
    $address = './assets/panel/excel/test123.xls';
    Excel::load($address, function($reader) {
        $results = $reader->get();
        dd($results);
    });
});

Laravel Excel is based on PHPExcel code by PHPOffice

One of the examples from PHPExcel documentation has the following code: https://github.com/PHPOffice/PHPExcel/blob/1.8/Documentation/Examples/Reader/exampleReader01.php#L29

Solution 2

You can use public_path() Laravel helper function as well:

Route::get('excel-test', function () {
    $address = public_path('assets/panel/excel/test123.xls');
    Excel::load($address, function($reader) {
        $results = $reader->get();
        dd($results);
    });
});

Discussion

Portion of a file that generates an error:

// /vendor/phpoffice/phpexcel/Classes/PHPExcel/Reader/Excel5.php
public function canRead($pFilename)
{
    // Check if file exists
    if (!file_exists($pFilename)) {
        throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist.");
    }
    // ...
}

As You can see PHPExcel uses file_exists() PHP function to check, if the file exists. file_exists() can check local path only and not the remote path / URL.