您的位置:首页 > 编程语言 > PHP开发

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

2017-07-05 13:49 615 查看
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'));


输出结果:



代码下载地址:

另参考:https://my.oschina.net/cgphp/blog/90792
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: