使用PHPExcel复制样式的解决方法

问题描述 投票:8回答:2

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

$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值用于所有重复的样式结果中。

我确信PHPExcel的将来版本将有修复程序,在此之前,我只需要找出解决方法。

phpexcel
2个回答
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中的repeatStyle()方法

当前从第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();
}

EDIT#2

现在已将修补程序推送到github上的developer分支。根据使用的样式数量,它确实会给性能带来轻微的影响。明天晚上我将尝试获得更快的版本


0
投票

以及如何使其与PhpSpreadsheet和php 7.4相关?在本地计算机工作中,在服务器生产中没有;(

© www.soinside.com 2019 - 2024. All rights reserved.