PHP tp框架实现excel表格导入

//导入
    public function addExcel()
    {

        $request=Request::instance();

        $excel = request()->file('excel')->getInfo();//excel为file中的name
        vendor("PHPExcel.Class.PHPExcel.IOFactory");
        $objPHPExcel = \PHPExcel_IOFactory::load($excel['tmp_name']);//读取上传的文件
        $arrExcel = $objPHPExcel->getSheet(0)->toArray();//获取其中的数据

        $word = $arrExcel[0];
        array_shift($arrExcel);

        $data = array();
        $num = count($arrExcel) -1;
        foreach ($arrExcel as $key => $value) {
            $data[] = array(

                'content'=>$arrExcel[$key][0]
            );
        }
        $result = Db::table('exceltable')->insertAll($data);
        if($result){
            $this->success('success');
        }else{
            $this->error('error');
        }
    }


    //导出
    public function excel(){
        $list=Db::table('eb_essas_message')->select();
        $file_name=date('Y-m-d_H:i:s').'.xls';
        dirname(__FILE__);
        Loader::import('PHPExcel.Classes.PHPExcel');
        Loader::import('PHPExcel.Classes.PHPExcel.IOFactory.PHPExcel_IOFactory');
        $PHPExcel = new \PHPExcel();
        $PHPSheet = $PHPExcel->getActiveSheet();
        $PHPSheet->setTitle("代理商");
        $PHPSheet->setCellValue("A1","ID");
        $PHPSheet->setCellValue("B1","名字");
        $PHPSheet->setCellValue("C1","电话");
        $PHPSheet->setCellValue("D1","编号");
        $i = 2;
        foreach($list as $key => $value){
            $PHPSheet->setCellValue('A'.$i,''.$value['id']);
            $PHPSheet->setCellValue('B'.$i,''.$value['name']);
            $PHPSheet->setCellValue('C'.$i,''.$value['cont']);
            $PHPSheet->setCellValue('D'.$i,''.$value['imag']);

            $i++;
        }
        $PHPWriter = \PHPExcel_IOFactory::createWriter($PHPExcel,"Excel2007");
        header('Content-Disposition: attachment;filename='.$file_name);
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        $PHPWriter->save("php://output");


    }

你可能感兴趣的:(php,excel,php)