简体   繁体   中英

How to read xls file in laravel - laravel-excel

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM