PHP读取Excel表格内容,并且将其转换成数组

来源:互联网 发布:linux下php的好处 编辑:程序博客网 时间:2024/04/29 22:57

Excel表格:


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

输出结果:


代码下载地址:

1
http://files.cnblogs.com/files/haveadream435/excel.rar
另参考:https://my.oschina.net/cgphp/blog/90792
原创粉丝点击