Search code examples
laravellaravel-excel

Laravel Excel handle error when file is open


I'm using Laravel Excel 2.1.0 in a local project to write a row into an excel file.

This is my code:

$filePath = storage_path('myfile.xls');
$rows = \Excel::load($filePath, function($reader) {
    $sheet = $reader->sheet(0);
    $sheet->appendRow(
        array(
             'Hello'
        )
    );
});

Everything works and a new line was appended to my file.

Sometimes can happens the excel file is opened while user try to append a new line. In this case Laravel, rightly, show me this error:

fopen(mypath\myfile.xls): failed to open stream: Resource temporarily unavailable

How can I handle this error in order to skip the function and go on with my code without append the row?


Solution

  • I solved in this way:

    $filePath = storage_path('myfile.xls');
    $fp = @fopen($filePath, "r+");
    if($fp) {
        $rows = \Excel::load($filePath, function($reader) {
            $sheet = $reader->sheet(0);
            $sheet->appendRow(
                array(
                     'Hello'
                )
            );
        });
    }