【发布时间】:2015-12-30 16:46:02
【问题描述】:
我是 phpexcel 新手,想将公式从一个单元格复制到其他单元格,就像在 excel 中一样。
我的程序从输入文件中读取数据,并在其中添加更多行,然后再保存到新文件中。输入表在单元格中有一些公式,例如在单元格C1中,公式为=A1*B1。
我想生成更多的 1 行,C2 中的公式是 A2*B2,这就像在 excel 中将单元格 C1 复制粘贴到 C2。
我如何用 phpexcel 做到这一点?
谢谢!
【问题讨论】:
我是 phpexcel 新手,想将公式从一个单元格复制到其他单元格,就像在 excel 中一样。
我的程序从输入文件中读取数据,并在其中添加更多行,然后再保存到新文件中。输入表在单元格中有一些公式,例如在单元格C1中,公式为=A1*B1。
我想生成更多的 1 行,C2 中的公式是 A2*B2,这就像在 excel 中将单元格 C1 复制粘贴到 C2。
我如何用 phpexcel 做到这一点?
谢谢!
【问题讨论】:
这没有捷径可走。您必须为每个单元格正确设置公式,因此您需要遍历设置公式的单元格,为每一行修改该公式:
for ($row = 1; $row <= 10; ++$row) {
$objPHPExcel->getActiveSheet()
->setCellValue(
'C' . $row,
'=A' . $row . '*B' . $row
);
}
【讨论】:
PHPExcel_ReferenceHelper 类的updateFormulaReferences() 方法,该方法在内部用于在插入/删除行/列时操作公式
我和你有同样的任务,所以这是我添加到 PHPExcel_Calculation_Parser 的静态方法。希望能帮到你:)。
/**
*
* @param numeric $rowNumber
*/
public static function cloneFormulaForRow($formula, $rowNumber, $rowFlag = 1) {
$formulaParser = new PHPExcel_Calculation_FormulaParser($formula);
$tokens = $formulaParser->getTokens();
$snips = [];
foreach ($tokens as $token) {
/* @var $token PHPExcel_Calculation_FormulaToken */
$type = $token->getTokenType();
$subType = $token->getTokenSubType();
$val = $token->getValue();
if ($type == 'Operand') {
if ($subType == 'Range') {
$cells = explode(':', $val);
foreach ($cells as &$cell) {
$cell = preg_replace_callback('/^([a-z]+)' . $rowFlag . '$/i', function($m)use($rowNumber) {
return $m[1] . $rowNumber;
}, $cell);
}
$snips[] = implode(':', $cells);
} else if ($subType == 'Text') {
$snips[] = ('"' . $val . '"');
} else {
//number
$snips[] = $val;
}
} else if ($type == 'Function' || $type == 'Subexpression') {
if ($subType == 'Start') {
$snips[] = '(';
} else {
$snips[] = ')';
}
} else if ($type == 'OperatorInfix') {
$snips[] = $val;
} else {
$snips[] = $val;
}
}
return '='. implode('', $snips);
}
例子:
PhpExcel_Calculation_Parser::cloneFormulaForRow("=SUM(A1:B1)",9) //"=SUM(A9:B9)"
【讨论】: