ci框架下的PHPExcel导出简单实例

用类库封装:

firstCell = $firstCell;
    }

    /**
     * @param $otherCell
     * 设置表格数组
     */
    public function setOtherCell($otherCell){
        $this->otherCell = $otherCell;
    }

    public function export($fileName){
        $excel = new PHPExcel();

        //填充表头信息
        $this->setExcelFristCell($excel);

        //填充表格信息
        $this->setExcelOtherCell($excel);

        //创建Excel输入对象
        $write = new PHPExcel_Writer_Excel5($excel);
        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.'.xls"');
        header("Content-Transfer-Encoding:binary");
        $write->save('php://output');
    }



    /**
     * @param $obj
     * 写入Excel第一行数据
     */
    private function setExcelFristCell($obj){
        for($i = 0;$i < count($this->firstCell);$i++) {
            $obj->getActiveSheet()->setCellValue($this->cellKey[$i]."1",$this->firstCell[$i]);
        }
    }

    /**
     * @param $obj
     * 写入Excel第一行以外的数组
     */
    private function setExcelOtherCell($obj){
        for ($i = 2;$i <= count($this->otherCell) + 1;$i++) {
            $j = 0;
            foreach ($this->otherCell[$i - 2] as $key=>$value) {
                $obj->getActiveSheet()->setCellValue($this->cellKey[$j].$i,"$value");
                $j++;
            }
        }

    }

}

controller调用:

public function exportExcelTest(){
        $this->load->library('excel_library');
        $cellName = array('a','b','c','d','e');
        $data = array(
            array('1','小王','男','20','100'),
            array('2','小李','男','20','101'),
            array('3','小张','女','20','102'),
            array('4','小赵','女','20','103')
        );
        $this->excel_library->setFirstCell($cellName);
        $this->excel_library->setOtherCell($data);
        $this->excel_library->export('demo');
    }

你可能感兴趣的:(日常類)