🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
> 有时候应用里会用到Excel导出,PHP做csv文件的导出比较简单,但Excel就比较复杂,这里推荐使用yii2的excel插件。 官网:https://github.com/PHPOffice/PHPExcel [TOC] #### 下载Excel插件 ~~~ composer require phpoffice/phpexcel "*" -v ~~~ #### 参考Example代码: ~~~ /vendor/phpoffice/phpexcel/Examples/01simple-download-xls.php //将该代码拷入Controller里运行即可,由于他的方法使用起来不是很方便,这里我选择封装方法,便于下次使用。 ~~~ #### 封装方法: ~~~ /** * @DESC 数据导 * @example * $data = [[1, "小明", "25"],[2, "王琨", "22"]]; * $header = ["id", "姓名", "年龄"]; * Myhelpers::exportEXCEL($data, $header); * @return void, Browser direct output */ static function exportEXCEL($data, $header, $title = "simple", $filename = "data"){ if (!is_array($data) || !is_array($header)) return false; $objPHPExcel = new \PHPExcel(); // Set properties $objPHPExcel->getProperties()->setCreator("Maarten Balliauw"); $objPHPExcel->getProperties()->setLastModifiedBy("Maarten Balliauw"); $objPHPExcel->getProperties()->setTitle("Office 2007 XLSX Test Document"); $objPHPExcel->getProperties()->setSubject("Office 2007 XLSX Test Document"); $objPHPExcel->getProperties()->setDescription("Test document for Office 2007 XLSX, generated using PHP classes."); //设置表头,也就是第一行数据 foreach ($header as $k => $v){ $column = \PHPExcel_Cell::stringFromColumnIndex($k); $objPHPExcel->setActiveSheetIndex(0) ->setCellValue($column."1", $v); } //设置行数据,从第二行开始 foreach ($data as $key=>$item){ foreach ($item as $key2=>$val){ $column = \PHPExcel_Cell::stringFromColumnIndex($key2); //获得列位置 // 添加一行数据,A1、B1、C1.....N1的各个数据 //设置为$key+2,因为key是从0开始,而我们的行数据第一个索引是“1”,而上面因为设置了表头,占了一行数据,所以就直接+2 $objPHPExcel->setActiveSheetIndex(0)->setCellValue($column.($key+2), $val); } } // Rename sheet $objPHPExcel->getActiveSheet()->setTitle($title); // Redirect output to a client’s web browser (Excel5) header('Content-Type: application/vnd.ms-excel'); header('Content-Disposition: attachment;filename="'.$filename.'.xls"'); header('Cache-Control: max-age=0'); // If you're serving to IE 9, then the following may be needed header('Cache-Control: max-age=1'); // If you're serving to IE over SSL, then the following may be needed header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1 header ('Pragma: public'); // HTTP/1.0 $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); $objWriter->save('php://output'); } ~~~