PHPExcel快速重复行

PHPExcel fast duplicate row

我为每个单元格设置了不同样式的行。我需要复制它(复制文本、样式、大小)。

我使用以下函数来完成:

  function copyRowFull(&$ws_from, &$ws_to, $row_from, $row_to) {
    $ws_to->getRowDimension($row_to)->setRowHeight($ws_from->getRowDimension($row_from)->getRowHeight());
    $lastColumn = $ws_from->getHighestColumn();
    $rangeFrom = 'A'.$row_from.':'.$lastColumn.$row_from;
    // copy text
    $ws_to->fromArray($ws_from->rangeToArray($rangeFrom), null, 'A'.$row_to);
    // copy style
    ++$lastColumn;
    for ($c = 'A'; $c != $lastColumn; ++$c) {
      $ws_to->duplicateStyle($ws_from->getStyle($c.$row_from), $c.$row_to);
    }
  }

然而,由于循环,它非常慢,但我需要它很快,因为将复制许多行。

我也试过这个来复制样式:

$rangeTo = 'A'.$row_to.':'.$lastColumn.$row_to;
$ws_to->getStyle($rangeTo)->applyFromArray($ws_from->getStyle($rangeFrom));

但它不起作用 - 抛出错误 "Invalid style array passed"。

有没有更快的方法?

在搜索 PHPExcel 源代码后,我找到了一种更快的复制行的方法。它只能在一个工作簿中进行复制,但这正是我所需要的。贴出来,也许有人也有或将会有类似的问题。

function copyRowFull(&$ws_from, &$ws_to, $row_from, $row_to) {
  $ws_to->getRowDimension($row_to)->setRowHeight($ws_from->getRowDimension($row_from)->getRowHeight());
  $lastColumn = $ws_from->getHighestColumn();
  ++$lastColumn;
  for ($c = 'A'; $c != $lastColumn; ++$c) {
    $cell_from = $ws_from->getCell($c.$row_from);
    $cell_to = $ws_to->getCell($c.$row_to);
    $cell_to->setXfIndex($cell_from->getXfIndex()); // black magic here
    $cell_to->setValue($cell_from->getValue());
  }
}

对于 PHP 5.3 左右的那些人,Somnium 的回答与 Ravean 的评论相结合并适用于 PHP 5.3:

    /**
 * Copies entire row with formatting and merging
 * @param $ws_from
 * @param $ws_to
 * @param $row_from
 * @param $row_to
 * @throws PHPExcel_Exception
 */
public function copyRowFull(&$ws_from, &$ws_to, $row_from, $row_to)
{
    $ws_to->getRowDimension($row_to)->setRowHeight($ws_from->getRowDimension($row_from)->getRowHeight());
    $lastColumn = $ws_from->getHighestColumn();
    ++$lastColumn;
    for ($c = 'A'; $c != $lastColumn; ++$c) {
        $cell_from = $ws_from->getCell($c . $row_from);
        if ($cell_from->isMergeRangeValueCell()) {
            $pCoordinateString = PHPExcel_Cell::splitRange($cell_from->getMergeRange());
            $coordinateFromString = PHPExcel_Cell::coordinateFromString($pCoordinateString[0][1]);
            $col = $coordinateFromString[0];
            $ws_to->mergeCells($c . $row_to . ':' . $col . $row_to);
            //$cell->getMergeRange()
        }
        $cell_to = $ws_to->getCell($c . $row_to);
        $cell_to->setXfIndex($cell_from->getXfIndex()); // black magic here
        $cell_to->setValue($cell_from->getValue());
    }
}