PHPExcel导出-根据数据动态填充值

代码

public function export()
    {
        include_once ROOT. 'opensource/phpexcel/PHPExcel.php';

        try {

            $objPHPExcel = new PHPExcel();

            $titleList = [
                '名称','年龄'
            ];
            $contentsList = [
                ['zs',10],
                ['ls',11],
                ['ww',12],
            ];

            $row = 1;//行
            $col = 0;//列
            foreach ($titleList as $value){
                $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $value);
                $col += 1;
            }
            
            foreach ($contentsList as $items){
                $row += 1;
                $col = 0;
                foreach ($items as $value) {
                    $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $value);
                    $col += 1;
                }
            }

            $filename = 'test'.date('ymdHis').'.xls';
            header("Content-Type: application/force-download");
            header("Content-Type: application/octet-stream");
            header("Content-Type: application/download");
            header('Content-Disposition:inline;filename="'.$filename.'"');
            $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
            $objWriter->save('php://output');
            exit;

        } catch (Exception $e) {
        }

    }

导出结果:

名称 年龄
zs 10
ls 11
ww 12
posted @ 2021-10-27 09:13  pine007  阅读(89)  评论(0编辑  收藏  举报