使用phpExcel读取一些单元格

时间:2013-01-07 17:22:10

标签: excel-formula phpexcel

我正在尝试使用过滤器阅读一些工作表,但问题是当这些单元格使用单元格时我无法获取单元格值

  $objReader = PHPExcel_IOFactory::createReader('Excel5');
  $objReader->setLoadSheetsOnly('Data Sheet #1');

  $myFilter = new CellReadFilter(1, 7, range('A', 'F'));
  $objReader->setReadDataOnly(true);
  $objReader->setReadFilter($myFilter);

  $objPHPExcel = $objReader->load('sampleData/example1.xls');

  $loadedSheetNames = $objPHPExcel->getSheetNames();
  foreach ($loadedSheetNames as $sheetIndex => $loadedSheetName) {
     echo $sheetIndex, ' => ', $loadedSheetName, '<br />';
     $sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
     var_dump($sheetData);
  }

我的excel文件,在F1单元格中,我使用以下公式:=C2,但我的脚本输出表明F1是null而不是预期的23.45。 / p>

 0 => Data Sheet #1

 array (size=3)
   1 => 
array (size=6)
  'A' => string 'Integer Numbers' (length=15)
  'B' => float 123
  'C' => float 234
  'D' => float -345
  'E' => float 456
  'F' => null
  2 => 
array (size=6)
  'A' => string 'Floating Point Numbers' (length=22)
  'B' => float 1.23
  'C' => float 23.45
  'D' => float 3.45E-6
  'E' => float -45.678
  'F' => float 56.78
  3 => 
array (size=6)
  'A' => string 'Strings' (length=7)
  'B' => string 'Hello' (length=5)
  'C' => string 'World' (length=5)
  'D' => null
  'E' => string 'PHPExcel' (length=8)
  'F' => null

我的单元格过滤器类在文档示例中显示:

class CellReadFilter implements PHPExcel_Reader_IReadFilter {

   private $_startRow = 0;
   private $_endRow = 0;
   private $_column = array();

   public function __construct($startRow, $endRow, $column) {
      $this->_startRow = $startRow;
      $this->_endRow = $endRow;
      $this->_column = array_merge($column, array('AA'));
   }

   public function readCell($column, $row, $worksheetName = '') {
      if ($row >= $this->_startRow && $row <= $this->_endRow) {
         if (in_array($column, $this->_column)) { return true; }
      }
      return false;
   }

}

1 个答案:

答案 0 :(得分:3)

验证您是否读取过滤器,修改readCell以测试正在应用的条件,以及确定哪些单元符合条件以及它们被接受/拒绝的原因:

public function readCell($column, $row, $worksheetName = '') {
    echo 'Testing worksheet ', $worksheetName, 'row ', $row, ' column ', $column, PHP_EOL;
    if ($row >= $this->_startRow && $row <= $this->_endRow) {
        'Cell is within row range',PHP_EOL;
        if (in_array($column, $this->_column)) { 
            'VALID: Cell is within column range',PHP_EOL;
            return true; 
        }
        'INVALID: Cell is outside column range',PHP_EOL;
    } else {
        'INVALID: Cell is outside row range',PHP_EOL;
    }
    return false;
}