【问题标题】:phpexcel duplicate formula just like excelphpexcel重复公式就像excel一样
【发布时间】:2015-12-30 16:46:02
【问题描述】:

我是 phpexcel 新手,想将公式从一个单元格复制到其他单元格,就像在 excel 中一样。

我的程序从输入文件中读取数据,并在其中添加更多行,然后再保存到新文件中。输入表在单元格中有一些公式,例如在单元格C1中,公式为=A1*B1。

我想生成更多的 1 行,C2 中的公式是 A2*B2,这就像在 excel 中将单元格 C1 复制粘贴到 C2。

我如何用 phpexcel 做到这一点?

谢谢!

【问题讨论】:

    标签: php phpexcel


    【解决方案1】:

    这没有捷径可走。您必须为每个单元格正确设置公式,因此您需要遍历设置公式的单元格,为每一行修改该公式:

    for ($row = 1; $row <= 10; ++$row) {
        $objPHPExcel->getActiveSheet()
            ->setCellValue(
                'C' . $row, 
                '=A' . $row . '*B' . $row
            );
    }
    

    【讨论】:

    • 谢谢。实际上我不知道输入文件中的公式到底是什么。有什么方法可以解析公式并为下一行生成新公式?
    • 不,没有简单的快捷方式....尽管您可以尝试使用PHPExcel_ReferenceHelper 类的updateFormulaReferences() 方法,该方法在内部用于在插入/删除行/列时操作公式
    • 谢谢!我试试看。
    【解决方案2】:

    我和你有同样的任务,所以这是我添加到 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)" 
    

    【讨论】:

      猜你喜欢
      • 2016-11-23
      • 2023-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-12
      相关资源
      最近更新 更多