·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> 网站建设开发 >> php网站开发 >> PHPExcel读取excel文件

PHPExcel读取excel文件

作者:佚名      php网站开发编辑:admin      更新时间:2022-07-23
phpExcel读取excel文件

PHPExcel是个很强大的类库,以前只使用过它生成Excel文件,非常方便。今天接到个项目要读取Excel的文件,以前也做过Excel转换写入数据库的工作,不过相对简单一些,是转换成CSV格式再进行解析的。首先下载PHPExcel类库。http://phpexcel.codeplex.com/包含PHPExcel类库文件,如果不能确定文件类型的话可以使用PHPExcel_IOFactory::identify方法返回文件的类型,传递给该函数一个文件名就可以。然后根据返回的文件类型创建该类型的读取对象,进行文件的load。之后就可以进行数据的读取了,具体代码如下所示:

    1. <?php
    2. require_once('include/common.inc.php');
    3. require_once(ROOTPATH.'include/phpExcel/PHPExcel/IOFactory.php');
    4. $filePath='./file/xls/110713.xls';
    5. $fileType=PHPExcel_IOFactory::identify($filePath);//文件名自动判断文件类型
    6. $objReader=PHPExcel_IOFactory::createReader($fileType);
    7. $objPHPExcel=$objReader->load($filePath);
    8. $currentSheet=$objPHPExcel->getSheet(0);//第一个工作簿
    9. $allRow=$currentSheet->getHighestRow();//行数
    10. $output=array();
    11. $PReType='';
    12. $qh=$currentSheet->getCell('A4')->getValue();
    13. //按照文件格式从第7行开始循环读取数据
    14. for($currentRow=7;$currentRow<=$allRow;$currentRow++){
    15. //判断每一行的B列是否为有效的序号,如果为空或者小于之前的序号则结束
    16. $xh=(int)$currentSheet->getCell('B'.$currentRow)->getValue();
    17. if(empty($xh))break;
    18. $tmpType=(string)$currentSheet->getCell('C'.$currentRow)->getValue();//赛事类型
    19. if(!empty($tmpType))$preType=$tmpType;
    20. $output[$xh]['type']=$preType;
    21. $output[$xh]['master']=$currentSheet->getCell('F'.$currentRow)->getValue();//主队
    22. $output[$xh]['guest']=$currentSheet->getCell('H'.$currentRow)->getValue();//客队
    23. }
    24. //从当前行开始往下循环,取出第一个不为空的行
    25. for(;;$currentRow++){
    26. $xh=(int)$currentSheet->getCell('B'.$currentRow)->getValue();
    27. if(!empty($xh))break;
    28. }
    29. for(;$currentRow<=$allRow;$currentRow++){
    30. $xh=(int)$currentSheet->getCell('B'.$currentRow)->getValue();
    31. if(empty($xh))break;
    32. $output[$xh]['rq']=$currentSheet->getCell('I'.$currentRow)->getValue();
    33. }
    34. header("content-type:text/html; charset=utf-8");
    35. echo'期号:'.$qh."\n\n";
    36. if(!empty($output)){
    37. printf("%-5s\t%-15s\t%-40s\t%-40s\t%-5s\n",'序号','赛事类型','主队','客队','让球值');
    38. foreach($outputas$key=>$row){
    39. $format="%-5d\t%-15s\t%-40s\t%-40s\t%-5s\n";
    40. printf($format,$key,$row['type'],$row['master'],$row['guest'],$row['rq']);
    41. }
    42. }
    43. ?>