错误引用 PHPExcel 中的单元格

Wrong reference to cell in PHPExcel

我正在开发基于 PHPExcel 库的导入器。

这段代码保存单元格供以后使用。

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

$this->_sheet 包含当前 sheet 这是有效的 PHPExcel_Worksheet 对象。

保存的单元格包含有效的 PHPExcel_Cell 对象。

稍后我也尝试在 foreach 循环中使用它:

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

    ...
}

$importModelAttribute->_defaultValueCell->getValue() returns 正确的值,但是 getCoordinate() returns 最后一行的第一个单元格的坐标 sheet (A11) 而它必须是 B7.

完成了一些其他计算,它们取决于单元格的样式(在本例中为颜色),并且它还 returns 来自 A11 单元格的样式。

出于测试和调试目的,我还尝试克隆单元格对象,但没有成功。

PHPExcel 中的单元格集合对象将一个单元格(最后引用的)保留为活动单元格....您的 $cell 对象实际上是指向该活动单元格的指针。

实际上,您对 setDefaultValueCell($cell); 的调用会将单元格指针存储在 $defaultValueCell 中,它将指向您进行调用时的正确单元格,但下一次迭代将调整指向新 $cell 值的指针,因为 tat 是新的 "active" 单元格。

您可以尝试 "cloning" 使用

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

但您最好将单元格 address/coordinate 存储在 $defaultValueCell 中,然后使用

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

在你的第二个循环中