php下载excel文件


如果只是为了下载文件直接在超链接中填写文件url地址即可。

如果文件下载需要给具有访问权限的人下载,则可以使用readfile函数:

$filename = 'filename.xlsx';
header('Content-Type: application/xlsx');
header('Content-Disposition: attachment;filename="'.$filename.'"');
header('Cache-Control: max-age=0');

readfile($filename);

如果需要动态生成excel文件内容可以像下面这样,在保存的时候将文件内容保存到输出流

$filename = 'filename.xlsx';
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="'.$filename.'"');
header('Cache-Control: max-age=0');
ob_start();
ob_flush();

$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('php://output');

Excel文件的xls后缀,MIME类型是:application/vnd.ms-excel

普人特福的博客cnzz&51la for wordpress,cnzz for wordpress,51la for wordpress