如何在php phpspreadsheet中使用excel求和公式?

kun*_*nal 8 php excel phpoffice phpspreadsheet

我正在使用 PhpSpreasdheet php 库。我已经完成了几乎所有我想要对特定列进行求和并想要显示该列的总计的操作。请参阅下面的我的输出:- 在此输入图像描述

我的预期输出如下:- 在此输入图像描述

我尝试过下面的代码:-

$spreadsheet = new Spreadsheet();
$Excel_writer = new Xlsx($spreadsheet);
$spreadsheet->setActiveSheetIndex(0);
$activeSheet = $spreadsheet->getActiveSheet();

$activeSheet->setCellValue('A1', 'Location');
$activeSheet->setCellValue('B1', 'Media Vehicle');
$activeSheet->setCellValue('C1', 'Dimension');
$activeSheet->setCellValue('D1', 'Amount');

$spreadsheet->getActiveSheet()->setAutoFilter('A1:D1');
    $locations = DB::table('locations')->get();
    $locations = json_decode(json_encode($locations),true);
    $i = 2;
    foreach($locations as $location){
        $activeSheet->setCellValue('A'.$i , $location['location']);
        $activeSheet->setCellValue('B'.$i , $location['media_vehicle']);
        $activeSheet->setCellValue('C'.$i , $location['dimension']);
        $activeSheet->setCellValue('D'.$i , $location['amount']);
        $i++;
    }

    $samplepath = storage_path('/excels/sampleExcel'.str_random(5).'.xlsx');
    $Excel_writer->save($samplepath);
    echo 'saved'; die;
Run Code Online (Sandbox Code Playgroud)

我想要金额列的总计。我想要动态化。如果将来它是 10 行,那么它将计算 10 行的金额列计数。

Sar*_*ees 8

在 phpspreadsheet 中您可以使用 Excel 公式。您所需要的只是要求和的数字范围。

$SUMRANGE = 'D2:D'.$i;
$activeSheet->setCellValue('D'.$i , '=SUM($SUMRANGE)');
Run Code Online (Sandbox Code Playgroud)


Ash*_*shu 1

你必须获得总第一:

第一个解决方案:

 $total = 0;
 foreach($locations as $location){
    $activeSheet->setCellValue('A'.$i , $location['location']);
    $activeSheet->setCellValue('B'.$i , $location['media_vehicle']);
    $activeSheet->setCellValue('C'.$i , $location['dimension']);
    $activeSheet->setCellValue('D'.$i , $location['amount']);
    $total = $total+$location['amount'];
    $i++;
}
//here your $i val already incremented in foreach() loop
$activeSheet->setCellValue('C'.$i , "Total");
$activeSheet->setCellValue('D'.$i , $total);
Run Code Online (Sandbox Code Playgroud)

第二个解决方案:

$activeSheet->setCellValue('C'.$i , "Total");
$spreadsheet->getActiveSheet()->getCell('D'.$i)->getCalculatedValue();
Run Code Online (Sandbox Code Playgroud)

我参考:https ://phpspreadsheet.readthedocs.io/en/stable/topics/calculation-engine/