This article mainly introduces how to quickly export excel return values in Laravel8. It is very simple~ I hope it will be helpful to friends in need!
[Related recommendations: laravel video tutorial]
Simple idea of exporting excel return value in Laravel8
Recently using Maatwebsite \Excel extension performs the export function of excel. I won’t go into details here about how to operate it. It is exported through the following code:
//导出excel【$head是excel表头,$list是数据】 return Excel::download(new CustomerExport($head, $list), date('YmdHis') . '.xls');
I printed this return value out of curiosity:
print_r(Excel::download(new CustomerExport($head, $list), date('YmdHis') . '.xls'));
The results are as follows:
Symfony\Component\HttpFoundation\BinaryFileResponse Object ( [file:protected] => Symfony\Component\HttpFoundation\File\File Object ( [pathName:SplFileInfo:private] => /home/vagrant/www/admin/storage/framework/cache/laravel-excel/laravel-excel-4U89uL9YLn4vNb1QrCDelsmv4Yrk3Ff.xls [fileName:SplFileInfo:private] => laravel-excel-4U89uL9YLn4vNb1QrCDelsmv4Yrk3Ff.xls ) [offset:protected] => 0 [maxlen:protected] => -1 [deleteFileAfterSend:protected] => 1 [headers] => Symfony\Component\HttpFoundation\ResponseHeaderBag Object ( [computedCacheControl:protected] => Array ( [public] => 1 ) [cookies:protected] => Array ( ) [headerNames:protected] => Array ( [cache-control] => Cache-Control [date] => Date [last-modified] => Last-Modified [content-disposition] => Content-Disposition ) [headers:protected] => Array ( [cache-control] => Array ( [0] => public ) [date] => Array ( [0] => Thu, 08 Dec 2022 05:57:26 GMT ) [last-modified] => Array ( [0] => Thu, 08 Dec 2022 07:16:21 GMT ) [content-disposition] => Array ( [0] => attachment; filename=20221208152026.xls ) ) [cacheControl:protected] => Array ( [public] => 1 ) ) [content:protected] => [version:protected] => 1.0 [statusCode:protected] => 200 [statusText:protected] => OK [charset:protected] => )
Obviously he is a target.
Because I separate the front-end and back-end, and the interface is directly coded above, the front-end students use the a tag to jump to the interface address for downloading, and it can be successful. But open the network of F12 to view the return value. What the front end gets is a file stream, as follows:
Why does running the interface directly return an object, but the front end gets it as a file? Flowed?
It turns out that when returning, two parameters are automatically added to the return header
Content-Disposition:attachment; filename=20221208152026.xls Content-Type:application/vnd.ms-excel
Content-Disposition is not the header message in the object
The above is the detailed content of How to quickly export excel return values in Laravel8!. For more information, please follow other related articles on the PHP Chinese website!