Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read xls file in laravel - laravel-excel

Tags:

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?

like image 332
S.M_Emamian Avatar asked May 18 '17 18:05

S.M_Emamian


1 Answers

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.

like image 52
Dmytro Dzyubak Avatar answered Sep 24 '22 10:09

Dmytro Dzyubak