首先,确保框架已经安装excle类,没有安装的话,执行以下操作
"phpoffice/phpexcel": "^1.8",
"phpoffice/phpspreadsheet": "^1.6",
将这两串代码放入composer.json下 框架执行composer update
php代码:
1 public function excelPhoto() 2 { 3 $res = Article::select(); 4 vendor("PHPExcel.PHPExcel"); 5 6 $resultPHPExcel = new \PHPExcel(); 7 //设置参数 8 9 //设值 10 11 $resultPHPExcel->getActiveSheet()->setCellValue('A1', 'id'); 12 $resultPHPExcel->getActiveSheet()->setCellValue('B1', '名称'); 13 $resultPHPExcel->getActiveSheet()->setCellValue('C1', '内容'); 14 $resultPHPExcel->getActiveSheet()->setCellValue('D1', '图片'); 15 $i = 2; 16 foreach ($res as $item) { 17 $resultPHPExcel->getActiveSheet()->setCellValue('A' . $i, $item['id']); 18 $resultPHPExcel->getActiveSheet()->setCellValue('B' . $i, $item['title']); 19 $resultPHPExcel->getActiveSheet()->setCellValue('C' . $i, $item['desc']); 20 $resultPHPExcel->getActiveSheet()->setCellValue('D' . $i, $item['img']); 21 $objDrawing = new \PHPExcel_Worksheet_Drawing(); 22 $objDrawing->setPath('.' . $item['img']);//这里拼接 . 是因为要在根目录下获取 23 // 设置宽度高度 24 $objDrawing->setHeight(50);//照片高度 25 $objDrawing->setWidth(50); //照片宽度 26 /*设置图片要插入的单元格*/ 27 $objDrawing->setCoordinates('C' . $i); 28 // 图片偏移距离 29 $objDrawing->setOffsetX(0); 30 $objDrawing->setOffsetY(0); 31 $objDrawing->setWorksheet($resultPHPExcel->getActiveSheet()); 32 $i++; 33 } 34 //设置导出文件名 35 36 $outputFileName = 'total.xls'; 37 38 $xlsWriter = new \PHPExcel_Writer_Excel5($resultPHPExcel); 39 40 ob_end_clean(); 41 header("Content-Type: application/force-download"); 42 43 header("Content-Type: application/octet-stream"); 44 45 header("Content-Type: application/download"); 46 47 header('Content-Disposition:inline;filename="' . $outputFileName . '"'); 48 49 header("Content-Transfer-Encoding: binary"); 50 51 header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); 52 53 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); 54 55 header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 56 57 header("Pragma: no-cache"); 58 59 $xlsWriter->save("php://output"); 60 }