坑:调用这个方法不能用ajax,如果用了ajax会在network里看到一堆乱码不会下载excel。
用a标签直接调用方法就行
引入类库
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
使用
public function downloadExcel(Request $request){
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
//设置sheet的名字 两种方法
$spreadsheet->getActiveSheet()->setTitle('Hello');
//设置第一行小标题
$k = 1;
$sheet->setCellValue('A'.$k, '商品名称');
$sheet->setCellValue('B'.$k, '价格');
$sheet->setCellValue('C'.$k, '分类');
$sheet->setCellValue('D'.$k, '描述');
$info = array(
['goods_name'=>'内衣','price'=>'11','category'=>'性感内衣','desc'=>'1111'],
['goods_name'=>'裙子','price'=>'80','category'=>'齐B短裙','desc'=>'1111'],
['goods_name'=>'裤子','price'=>'60','category'=>'七分裤','desc'=>'1111'],
['goods_name'=>'袜子','price'=>'70','category'=>'连体丝袜','desc'=>'1111']
);
$k = 2;
foreach ($info as $key => $value) {
$sheet->setCellValue('A' . $k, $value['goods_name']);
$sheet->setCellValue('B' . $k, $value['price']);
$sheet->setCellValue('C' . $k, $value['category']);
$sheet->setCellValue('D' . $k, $value['desc']);
$k++;
}
$file_name = date('Y-m-d', time()).rand(1000, 9999);
$file_name = $file_name . ".xlsx";
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$file_name.'"');
header('Cache-Control: max-age=0');
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('php://output');
}