php实现导出excel功能(转)

写在前面:马上面临着毕业设计的系统检查,为避免bug侧漏,不断的进行项目优化,目前在bug池中已经游走了一两天了,重要的是自己在bug池游走的过程中还不忘记给自己增加新的功能,比如,我认为加一个批量的导出功能可以为毕业设计提分,omg,说一不二开始捯饬excel导出;

问题:如何自定义的导出,如何定义自己想要的模板呢?

1.首先下载phpExcel 文件 https://pan.baidu.com/s/1ITnaVJ1n6pujku3YgMc-7w  提取码: nb4m  

2.解压文件到php的vender的文件夹下面

3.进行编写导出的代码

  在cntroller中新建立一个文件(防止与其他的逻辑代码混合)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
public function clubpeople(){<br>//可以进行自定义传值,比如一个id,去向数据库找那个取出值
    if(isset($_GET['club_id'])){
        $clubid=$_GET['club_id'];
    }
    //获取到get参数
            //1.从数据库中导出需要进行要导出的数据
            $list =Db::query('SELECT stu_list.stu_name,stu_list.stu_department,stu_list.stu_phone,stu_list.stu_email,stu_list.stu_profess
            ,club_branch.* FROM club_branch INNER JOIN stu_list ON club_branch.stu_number = stu_list.stu_number
             where club_branch.club_id=:acc order by club_branch.club_branch_name ',['acc'=>$clubid]);
              
    //重要补助
        //2.加载PHPExcle类库
        vendor('PHPExcel.PHPExcel');
        //3.实例化PHPExcel类
        $objPHPExcel = new \PHPExcel();
        //4.激活当前的sheet表
        $objPHPExcel->setActiveSheetIndex(0);
        //5.设置表格头(即excel表格的第一行)
        $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A1''部门')
                ->setCellValue('B1''职位')
                ->setCellValue('C1''学号')
                ->setCellValue('D1''学生姓名')
                ->setCellValue('E1''联系方式')
                ->setCellValue('F1''邮箱')
                ->setCellValue('G1''院系')
                ->setCellValue('H1''专业');
        //设置A列水平居中
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('A1')->getAlignment()
                    ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        //设置单元格宽度
        //6.循环刚取出来的数组,将数据逐一添加到excel表格。
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('B')->setWidth(10);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('C')->setWidth(20);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('E')->setWidth(20);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('F')->setWidth(30);
          
        for($i=0;$i<count($list);$i++){
            $objPHPExcel->getActiveSheet()->setCellValue('A'.($i+2),$list[$i]['club_branch_name']);//ID
            $objPHPExcel->getActiveSheet()->setCellValue('B'.($i+2),$list[$i]['club_position']);//标签码
            $objPHPExcel->getActiveSheet()->setCellValue('C'.($i+2),$list[$i]['stu_number']);//防伪码
            $objPHPExcel->getActiveSheet()->setCellValue('D'.($i+2),$list[$i]['stu_name']);//ID
            $objPHPExcel->getActiveSheet()->setCellValue('E'.($i+2),$list[$i]['stu_phone']);//标签码
            $objPHPExcel->getActiveSheet()->setCellValue('F'.($i+2),$list[$i]['stu_email']);//ID
            $objPHPExcel->getActiveSheet()->setCellValue('G'.($i+2),$list[$i]['stu_department']);//标签码
            $objPHPExcel->getActiveSheet()->setCellValue('H'.($i+2),$list[$i]['stu_profess']);//防伪码
        }
        //7.设置保存的Excel表格名称
        $filename = $club_name.'人员名单'.date('ymd',time()).'.xls';
        //8.设置当前激活的sheet表格名称;
        $objPHPExcel->getActiveSheet()->setTitle('人员名单');
        //9.设置浏览器窗口下载表格
        header("Content-Type: application/force-download"); 
        header("Content-Type: application/octet-stream"); 
        header("Content-Type: application/download"); 
        header('Content-Disposition:inline;filename="'.$filename.'"'); 
        //生成excel文件
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        //下载文件在浏览器窗口
        $objWriter->save('php://output');
        exit;
}

  这样一个下载的表格就完成了,

2:如何进行解析表格存放在数据库中呢

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public function getExcel(){ <br>//首先要判断当前是否与文件传过来,并判断文件传输是否正确
   if(isset($_FILES["file"]) && ($_FILES["file"]["error"] == 0)){       
          $file = $_FILES['file'];
          $path = $file['tmp_name'];
            //读取excel
             $arr = $this->excel($path, 0);
             $result =$arr;//用来记录当前操作的错误之类的
             //当解析完数据结构之后,就可以进行实地的插入数据库操作了,此处省略掉这个部分~
   
       $number = mt_rand(999, 9999);//随机数返回前端,取名字
       session('file'.$number ,$arg);  //保存当前的一个报告结果数组,可以对报告进行下载
       $resultr['status']=1;
       $resultr['msg']= $number;
       return json($resultr);
       
   }else{
       $resultarr['status']=0;
       $resultarr['msg']='文件上传发生错误,,稍后再试';
       return json($resultarr);
   }
    
   }

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public function excel($filePath='', $sheet=0){
                  
                  import("Org.Util.PHPExcel");
                  import("Org.Util.PHPExcel.Reader.Excel5");
                 import("Org.Util.PHPExcel.Reader.Excel2007");
          
                 if(empty($filePath) or !file_exists($filePath)){die('file not exists');}
                 $PHPReader = new \PHPExcel_Reader_Excel2007();        //建立reader对象
                 if(!$PHPReader->canRead($filePath)){
                     $PHPReader = new \PHPExcel_Reader_Excel5();
                    if(!$PHPReader->canRead($filePath)){
                          echo 'no Excel';
                        return ;
                      }
                 }
                 $PHPExcel = $PHPReader->load($filePath);        //建立excel对象
                 $currentSheet = $PHPExcel->getSheet($sheet);        //**读取excel文件中的指定工作表*/
                $allColumn = $currentSheet->getHighestColumn();        //**取得最大的列号*/
                $allRow = $currentSheet->getHighestRow();        //**取得一共有多少行*/
                 $data = array();
                 for($rowIndex=1;$rowIndex<=$allRow;$rowIndex++){        //循环读取每个单元格的内容。注意行从1开始,列从A开始
                     for($colIndex='A';$colIndex<=$allColumn;$colIndex++){
                         $addr = $colIndex.$rowIndex;
                         $cell = $currentSheet->getCell($addr)->getValue();
                         if($cell instanceof PHPExcel_RichText){ //富文本转换字符串
                             $cell = $cell->__toString();
                         }
                         $data[$rowIndex][$colIndex] = $cell;
                     }
                 }
                 return $data;
             }
            

  

omg~~三段代码完成的功能分别是导出excel,还有就是上传excel,然后可以进行解析,

posted on 2021-09-29 17:00  剩余价值  阅读(2237)  评论(0编辑  收藏  举报

导航