PHPExcel读取excel文件示例

jerry PHP 2018年07月31日 收藏

PHPExcel是一个非常方便生成Excel格式文件的类,官方下载包中带有大量如何生成各种样式excel文件的示例,但没有一个读取Excel文件的完整例子.Xiaoqiang根据网上的资料,整理了一份简单读取Excel文件的例子. 传统方法:

  1. <?php
  2. /**
  3.  *
  4.  * @copyright 2007-2012 Xiaoqiang.
  5.  * @author Xiaoqiang.Wu <jamblues@gmail.com>
  6.  * @version 1.01
  7.  */
  8.  
  9. error_reporting(E_ALL);
  10.  
  11. date_default_timezone_set('Asia/ShangHai');
  12.  
  13. /** PHPExcel_IOFactory */
  14. require_once '../Classes/PHPExcel/IOFactory.php';
  15.  
  16.  
  17. // Check prerequisites
  18. if (!file_exists("31excel5.xls")) {
  19.     exit("not found 31excel5.xls.\n");
  20. }
  21.  
  22. $reader = PHPExcel_IOFactory::createReader('Excel5'); //设置以Excel5格式(Excel97-2003工作簿)
  23. $PHPExcel = $reader->load("31excel5.xls"); // 载入excel文件
  24. $sheet = $PHPExcel->getSheet(0); // 读取第一個工作表
  25. $highestRow = $sheet->getHighestRow(); // 取得总行数
  26. $highestColumm = $sheet->getHighestColumn(); // 取得总列数
  27. $highestColumm= PHPExcel_Cell::columnIndexFromString($colsNum); //字母列转换为数字列 如:AA变为27
  28.  
  29. /** 循环读取每个单元格的数据 */
  30. for ($row = 1; $row <= $highestRow; $row++){//行数是以第1行开始
  31.     for ($column = 0; $column < $highestColumm; $column++) {//列数是以第0列开始
  32.         $columnName = PHPExcel_Cell::stringFromColumnIndex($column);
  33.         echo $columnName.$row.":".$sheet->getCellByColumnAndRow($column, $row)->getValue()."<br />";
  34.     }
  35. }
  36.  
  37. ?>

精简方法:

  1. <?php
  2. /**
  3.  *
  4.  * @copyright 2007-2012 Xiaoqiang.
  5.  * @author Xiaoqiang.Wu <jamblues@gmail.com>
  6.  * @version 1.01
  7.  */
  8.  
  9. error_reporting(E_ALL);
  10.  
  11. date_default_timezone_set('Asia/ShangHai');
  12.  
  13. /** PHPExcel_IOFactory */
  14. require_once '../Classes/PHPExcel/IOFactory.php';
  15.  
  16.  
  17. // Check prerequisites
  18. if (!file_exists("31excel5.xls")) {
  19.     exit("not found 31excel5.xls.\n");
  20. }
  21.  
  22. $reader = PHPExcel_IOFactory::createReader('Excel5'); //设置以Excel5格式(Excel97-2003工作簿)
  23. $PHPExcel = $reader->load("31excel5.xls"); // 载入excel文件
  24. $sheet = $PHPExcel->getSheet(0); // 读取第一個工作表
  25. $highestRow = $sheet->getHighestRow(); // 取得总行数
  26. $highestColumm = $sheet->getHighestColumn(); // 取得总列数
  27.  
  28. /** 循环读取每个单元格的数据 */
  29. for ($row = 1; $row <= $highestRow; $row++){//行数是以第1行开始
  30.     for ($column = 'A'; $column <= $highestColumm; $column++) {//列数是以A列开始
  31.         $dataset[] = $sheet->getCell($column.$row)->getValue();
  32.         echo $column.$row.":".$sheet->getCell($column.$row)->getValue()."<br />";
  33.     }
  34. }
  35.  
  36. ?>

PHPExcel最新版下载: http://phpexcel.codeplex.com/