首页 > 代码库 > yii2 中excel表导出

yii2 中excel表导出

首先下载phpexcel

在引入类文件(在web中index.php入口文件或者控制器中引入)

require_once dirname(dirname(__FILE__)).‘/excel/PHPExcel.php‘;
require_once dirname(dirname(__FILE__)).‘/excel/PHPExcel/IOFactory.php‘;
require_once dirname(dirname(__FILE__)).‘/excel/PHPExcel/Reader/Excel5.php‘;
require_once dirname(dirname(__FILE__)).‘/excel/PHPExcel/Reader/Excel2007.php‘;

然后在控制器中写

public  function actionExport()
{
         $objPHPExcel = new \PHPExcel();
        /*以下是一些设置 ,什么作者  标题啊之类的*/
        $objPHPExcel->getProperties()->setCreator("电影")
            ->setLastModifiedBy("电影")
            ->setTitle("数据EXCEL导出")
            ->setSubject("数据EXCEL导出")
            ->setDescription("备份数据")
            ->setKeywords("excel")
            ->setCategory("result file");
        //测试数据
        $sql="select order_id,user_true_name,movie,seat,order_num from orders ";
        $data = http://www.mamicode.com/yii::$app->db->createCommand($sql)->queryAll();

   //excel表中表头
        $title=array(‘order_id‘=>‘id‘,‘user_true_name‘=>‘账号姓名‘,‘movie‘=>‘电影名称‘,‘seat‘=>‘座位‘,‘order_num‘=>‘订单号‘);
        Array_unshift($data,$title);
//        print_r($data);die;
        /*以下就是对处理Excel里的数据, 横着取数据,主要是这一步,其他基本都不要改*/
        foreach($data as $k => $v){
            $num=$k+1;
            $objPHPExcel->setActiveSheetIndex(0)

                //Excel的第A列,uid是你查出数组的键值,下面以此类推
                ->setCellValue(‘A‘.$num, $v[‘order_id‘]) //A1 A2
                ->setCellValue(‘B‘.$num, $v[‘user_true_name‘])
                 ->setCellValue(‘C‘.$num, $v[‘movie‘])
                ->setCellValue(‘D‘.$num, $v[‘seat‘])
                 ->setCellValue(‘E‘.$num, $v[‘order_num‘]);
//                ->setCellValue(‘F‘.$num, $v[‘cate_id‘]);
                 
        }
        //设置活动工作簿的标题
        $objPHPExcel->getActiveSheet()->setTitle(‘1502E‘);
        //设置当前工作簿为第一个工作簿
        $objPHPExcel->setActiveSheetIndex(0);
        //以文件下载的方式输出
        header(‘Content-Type: application/vnd.ms-excel‘);
        header(‘Content-Disposition: attachment;filename="‘.time().‘.xlsx"‘);
        header(‘Cache-Control: max-age=0‘);
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, ‘Excel5‘);
        $objWriter->save(‘php://output‘);
    }

 

yii2 中excel表导出