首页 > 代码库 > Thinkphp3.2 PHPexecl 导出

Thinkphp3.2 PHPexecl 导出

1 下载phpexecl  放入到tp里边。

路径如下:项目根目录\ThinkPHP\Library\Org\Util

技术分享

 

2  PHP 代码部分 

封装一个方法

private  function getExcel($fileName,$headArr,$data){
        //导入PHPExcel类库,因为PHPExcel没有用命名空间,只能inport导入
        import("Org.Util.PHPExcel");
        import("Org.Util.PHPExcel.Writer.Excel5");
        import("Org.Util.PHPExcel.IOFactory.php");

        $date = date("Y_m_d",time());
        $fileName .= "_{$date}.xls";

        //创建PHPExcel对象,注意,不能少了\
        $objPHPExcel = new \PHPExcel();
        $objProps = $objPHPExcel->getProperties();

        //设置表头
        $key = ord("A");
        //print_r($headArr);exit;
        foreach($headArr as $v){
            $colum = chr($key);
            $objPHPExcel->setActiveSheetIndex(0) ->setCellValue($colum.‘1‘, $v);

            $objPHPExcel->setActiveSheetIndex(0) ->setCellValue($colum.‘1‘, $v);
            $key += 1;
        }

        $column = 2;
        $objActSheet = $objPHPExcel->getActiveSheet();

        //print_r($data);exit;
        foreach($data as $key => $rows){ //行写入
            $span = ord("A");
            foreach($rows as $keyName=>$value){// 列写入
                $j = chr($span);
                $objActSheet->setCellValue($j.$column, $value);
                $span++;
            }
            $column++;
        }

        $fileName = iconv("utf-8", "gb2312", $fileName);

        //重命名表
        //$objPHPExcel->getActiveSheet()->setTitle(‘test‘);
        //设置活动单指数到第一个表,所以Excel打开这是第一个表
        $objPHPExcel->setActiveSheetIndex(0);
        ob_end_clean();//清除缓冲区,避免乱码
        header(‘Content-Type: application/vnd.ms-excel‘);
        header("Content-Disposition: attachment;filename=\"$fileName\"");
        header(‘Cache-Control: max-age=0‘);

        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, ‘Excel5‘);
        $objWriter->save(‘php://output‘); //文件通过浏览器下载
        exit;
    }

 

 数据导出方法

public function index(){
    $user=M(‘table‘);
    $data=$user->select();
    foreach ($data as $key => $value) {
        $data[$key][id]=$value[‘id‘];
        $data[$key][name]=$value[‘name‘];
        $data[$key][sex]=$value[‘sex‘];
        $data[$key][content]=$value[‘content‘];
    }
    foreach ($data as $filed => $value) {
       if($filed== ‘id‘){$headArr[]=‘序号‘;}
       if($filed== ‘name‘){$headArr[]=‘名字‘;}
       if($filed== ‘sex‘){$headArr[]=‘性别‘;}
       if($filed== ‘content‘){$headArr[]=‘备注‘;}
   }
        
   $filename="测试";  //文件名字
   $this->getExcel($filename,$headArr,$data); 
  
    }

 

 

3 访问index方法   ok了!

Thinkphp3.2 PHPexecl 导出