php导出excel表

public function exportExcel() {
        $data = [
            [‘name‘ => ‘aa‘, ‘telephone‘ => ‘133xxxx4851‘],
            [‘name‘ => ‘bb‘, ‘telephone‘ => ‘135xxxx5862‘],
            [‘name‘ => ‘cc‘, ‘telephone‘ => ‘136xxxx6873‘],
            [‘name‘ => ‘dd‘, ‘telephone‘ => ‘137xxxx7884‘]
        ];
        $objPHPExcel = new \PHPExcel();
        if (empty($filename)) $filename = date(‘Y-m-d H:i:s‘, time());

        $objActSheet = $objPHPExcel->getActiveSheet();
        $objActSheet->setTitle("用户信息表");

        //设置表头
        $names = [
            ‘A‘ => ‘名字‘, ‘B‘ => ‘手机号‘
        ];

        foreach ($names as $key => $value) {
            // 水平居中
            $objActSheet->getStyle($key)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            // 垂直居中
            $objActSheet->getStyle($key)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            //设置宽
            $objActSheet->getColumnDimension($key)->setWidth(20);
            //设置列名
            $name = $key . ‘1‘;

            $objActSheet->setCellValue($name, $value);
            //设置字体
            $objActSheet->getStyle($name)->getFont()->setBold(true);
        }

        //设置数据

        foreach ($data as $k => $v) {
            $name = ArrayHelper::getValue($v, ‘name‘);
            $telephone = ArrayHelper::getValue($v, ‘telephone‘);
            $k += 2;
            $objActSheet
                ->setCellValueExplicit(‘A‘ . $k, $name)
                ->setCellValue(‘B‘ . $k, $telephone);
        }
        $objActSheet->freezePane(‘A2‘);

        //设输出格式
        $objWriter = new \PHPExcel_Writer_Excel2007($objPHPExcel);

        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="‘ . $filename . ‘.xlsx‘);
        header("Content-Transfer-Encoding:binary");

        $objWriter->setPreCalculateFormulas(true);
        $objWriter->save(‘php://output‘);
    }

相关推荐