yii2 中使用 phpexcel 导出 excel
转自 http://www.yiichina.com/tutorial/1424
public function actionDownexcel() { //要使用的数据 $repair_infos = ConDbRepair::find()->asArray()->all(); //实例化 $objPHPExcel = new \PHPExcel(); $objWriter = new \PHPExcel_Writer_Excel5($objPHPExcel); //这里是显示的标题字段 也就是你数据库的字段名称 $objPHPExcel->getActiveSheet()->setCellValue('A1', '日期');//这里是设置 A1 单元格的内容 $objPHPExcel->getActiveSheet()->setCellValue('B1', '维修名称');////这里是设置 B1 单元格的内容 $objPHPExcel->getActiveSheet()->setCellValue('C1', '维修类型');////这里是设置 B1 单元格的内容 $objPHPExcel->getActiveSheet()->setCellValue('D1', '消耗库存');////这里是设置 B1 单元格的内容 $objPHPExcel->getActiveSheet()->setCellValue('E1', '维修费用');////这里是设置 B1 单元格的内容 $objPHPExcel->getActiveSheet()->setCellValue('F1', '成本');////这里是设置 B1 单元格的内容 $objPHPExcel->getActiveSheet()->setCellValue('G1', '毛利');////这里是设置 B1 单元格的内容 //这里是每条数据的内容了 foreach ($repair_infos as $key => $value) { $i=$key+2;//表格是从 1 开始的 $objPHPExcel->getActiveSheet()->setCellValue('A'.$i, $value['update_time']); $objPHPExcel->getActiveSheet()->setCellValue('B'.$i, $value['repair_name']); $objPHPExcel->getActiveSheet()->setCellValue('C'.$i, $value['repair_name']); $objPHPExcel->getActiveSheet()->setCellValue('D'.$i, $value['repair_price']); $objPHPExcel->getActiveSheet()->setCellValue('E'.$i, $value['repair_name']); $objPHPExcel->getActiveSheet()->setCellValue('F'.$i, $value['repair_price']); $objPHPExcel->getActiveSheet()->setCellValue('G'.$i, $value['repair_price']); } //接下来当然是下载这个表格了,在浏览器输出就好了 $file_name = date('YmdHis'); header("Pragma: public"); header("Expires: 0"); header("Cache-Control:must-revalidate, post-check=0, pre-check=0"); header("Content-Type:application/force-download"); header("Content-Type:application/vnd.ms-execl"); header("Content-Type:application/octet-stream"); header("Content-Type:application/download");; header('Content-Disposition:attachment;filename='.$file_name.'.xls'); header("Content-Transfer-Encoding:binary"); $objWriter->save('php://output'); }