每个单元格都有不同样式的行。我需要复制它(复制文本,样式,大小)。
我正在使用以下功能来执行此操作:
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));
但它不起作用 - 抛出错误"传递的样式数组无效"。
有更快的方法吗?
答案 0 :(得分:7)
在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());
}
}
答案 1 :(得分:0)
对于使用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());
}
}