PHP导出excel

//此方法导出excel,$data的键值必须是0,1,2...这样的数组

public function export_cand($data,$projname,$num)
{
        // 内存加大
        ini_set('memory_limit','2048M');
        //引入PHPExcel库文件
        include '../application/helpers/PHPExcel.php';
        //创建对象
        $excel = new PHPExcel();
        $biaotou = 'A';
        $n = 1;
        while ($n++ <= $num) {
            $biaotou++;
        }
        for($k='A'; $k != $biaotou; $k++) $letter[] = $k;
        //表头数组
        $tableheader = array('序号','人员姓名','导入时间','详情连接');
        //填充表头信息
        for( $i=0; $i < count($tableheader); $i++ ){
            $excel->getActiveSheet()->setCellValue("$letter[$i]1","$tableheader[$i]");
        }
        $excel->getActiveSheet()->getColumnDimension('D')->setAutoSize(true);
        //填充表格信息
        for( $i = 2; $i <= count($data) + 1; $i++){
            $j = 0;
            foreach($data[$i-2] as $key => $value){
                $excel->getActiveSheet()->getCell('D'.$i)->getHyperlink()->setUrl('http://'.$data[$i-2][3]);
                $excel->getActiveSheet()->setCellValue("$letter[$j]$i","$value");
                $j++;
            }
        }
        //创建excel输入对象
        $write = new PHPExcel_Writer_Excel2007($excel);

   //如果header头起冲突
        $filename = ini_get('upload_tmp_dir').'/cmbc_'.time().'.xlsx';
        $write->save($filename);
        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="['.$projname.'].xlsx"');
        header("Content-Transfer-Encoding:binary");
        $filepath = './canddata/cand_detail.excel';
        // $write->save('php://output');
        echo file_get_contents($filename);
        @unlink($filename);

}

posted @ 2018-06-12 11:37  王浩栋  阅读(155)  评论(0编辑  收藏  举报