9

我想将样式信息从单元格复制到范围,例如 Excel 中的格式刷。文档说要做这样的事情:

$activeSheet->duplicateStyle($activeSheet->getStyle('A1'), 'D1:D100');
$activeSheet->duplicateStyle($activeSheet->getStyle('B1'), 'E1:E100');

似乎有一个错误,因为 D1:D100 和 E1:E100 都从单元格 B1 获取样式。如果我更改两行的顺序,则两个范围都从 A1 获取样式。相似地,

$styleA = $activeSheet->getStyle('A1');
$styleB = $activeSheet->getStyle('B1');
$activeSheet->duplicateStyle($styleA, 'D1:D100');

导致 D1:D100 从单元格 B1 获取样式信息。最后一个 getStyle 值用于所有 duplicateStyle 结果。

我确信 PHPExcel 的未来版本会有一个修复,我只需要在那之前找出一个解决方法。

4

1 回答 1

13

一种解决方法可能是使用样式 xf 索引:

$xfIndex = $activeSheet->getCell('A1')->getXfIndex();

然后为范围内所有单元格的 xfIndex 设置该值

for ($col = 'D'; $col != 'E'; ++$col) {
    for ($row = 1; $row <= 100; ++$row) {
        $activeSheet->getCell($col . $row)->setXfIndex($xfIndex);
    }
}

编辑

或者,将修复应用于 Classes/PHPExcel/Worksheet.php 中的 duplicateStyle() 方法

第 1479 至 1486 行当前为:

if ($this->_parent->cellXfExists($pCellStyle)) {
    // there is already this cell Xf in our collection
    $xfIndex = $pCellStyle->getIndex();
} else {
    // we don't have such a cell Xf, need to add
    $workbook->addCellXf($pCellStyle);
    $xfIndex = $pCellStyle->getIndex();
}

改成:

if ($existingStyle = $this->_parent->getCellXfByHashCode($pCellStyle->getHashCode())) {
    // there is already such cell Xf in our collection
    $xfIndex = $existingStyle->getIndex();
} else {
    // we don't have such a cell Xf, need to add
    $workbook->addCellXf($pCellStyle);
    $xfIndex = $pCellStyle->getIndex();
}

同样在 Classes/PHPExcel/Style.php 中的 applyFromArray() 方法中

第 425 至 432 行当前为:

if ($workbook->cellXfExists($newStyle)) {
    // there is already such cell Xf in our collection
    $newXfIndexes[$oldXfIndex] = $existingStyle->getIndex();
} else {
    // we don't have such a cell Xf, need to add
    $workbook->addCellXf($newStyle);
    $newXfIndexes[$oldXfIndex] = $newStyle->getIndex();
}

改成:

if ($existingStyle = $workbook->getCellXfByHashCode($newStyle->getHashCode())) {
    // there is already such cell Xf in our collection
    $newXfIndexes[$oldXfIndex] = $existingStyle->getIndex();
} else {
    // we don't have such a cell Xf, need to add
    $workbook->addCellXf($newStyle);
    $newXfIndexes[$oldXfIndex] = $newStyle->getIndex();
}

编辑#2

修复现已推送到 github 上的开发分支。它确实会对性能产生轻微影响,具体取决于使用的样式数量......我明天晚上会尝试获得更快的版本

于 2013-08-15T21:59:51.327 回答