1

I'm developing importer based on PHPExcel library.

This piece of code saves the cells for later usage.

foreach ($this->importModel->currentAttributeNames as $columnLabel => $attribute) {
    $cell = $this->_sheet->getCell($columnLabel . $row->getRowIndex());
    $this->importModel->importModelAttributes[$attribute]->setDefaultValueCell($cell);         
}

$this->_sheet contains current sheet which is valid PHPExcel_Worksheet object.

Saved cells contain valid PHPExcel_Cell object.

Later I try to use it also in foreach loop:

foreach ($this->importModel->importModelAttributes as $importModelAttribute) {
    var_dump($importModelAttribute->_defaultValueCell);

    ...
}

$importModelAttribute->_defaultValueCell->getValue() returns correct value, but getCoordinate() returns the coordinate of first cell of the last row with data in this sheet (A11) while it must be B7.

Some other calculations are done and they depend on style of the cells (color in this case), and it also returns style from A11 cell.

For testing and debugging purposes I also tried to clone cell objects but with no success.

arogachev
  • 33,150
  • 7
  • 114
  • 117

1 Answers1

2

The cell collection object in PHPExcel keeps one cell (the last referenced) as an active cell.... your $cell object is effectively a pointer pointing to that one active cell.

In practical terms, your call to setDefaultValueCell($cell); will store the cell pointer in $defaultValueCell, which will be pointing to the correct cell at the point where you make the call, but the next iteration will adjust that the pointer to the new $cell value, because tat is the new "active" cell.

You could try "cloning" using

$cell = clone $this->_sheet->getCell($columnLabel . $row->getRowIndex());

but you're probably better just storing the cell address/coordinate in $defaultValueCell and then using

foreach ($this->importModel->importModelAttributes as $importModelAttribute) {
    $cell = $this->_sheet->getCell($importModelAttribute->_defaultValueCell)
    ...
}

in your second loop

Mark Baker
  • 209,507
  • 32
  • 346
  • 385
  • Thanks for explanation. I actually thought about storing coordinate and sheet number as alternative. If I call `getCell($coordinate)` again where it will be loaded from? From cache or will be processed again? In other words, how it will affect perfomance? – arogachev Mar 16 '15 at 15:26
  • 1
    Another call to getCell() will reload that cell from cache (if it's cached) and reset it as the active cell... how much of a performance overhead this is will depend on the caching that you're using – Mark Baker Mar 16 '15 at 15:27