PHPExcel读取excel文件

王朝学院·作者佚名  2016-05-25
窄屏简体版  字體: 小  |  中  |  大  |  超大  

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

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

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航