如何在php phpspreadsheet中使用Excel sum公式?

时间:2019-03-01 06:47:30

标签: php excel phpspreadsheet

我正在使用PhpSpreasdheet php库。我几乎已经做了所有我想对特定列求和并希望显示该列的总数的所有操作。请参阅下面的我的输出:- enter image description here

我的预期输出如下: enter image description here

我尝试了以下代码:-

$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;

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

3 个答案:

答案 0 :(得分:0)

您必须合计获得第一名:

第一个解决方案:

 $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);

第二种解决方法:

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

有人推荐我:https://phpspreadsheet.readthedocs.io/en/stable/topics/calculation-engine/

答案 1 :(得分:0)

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

$SUMRANGE = 'D2:D'.$i;
$activeSheet->setCellValue('D'.$i , '=SUM($SUMRANGE)');

答案 2 :(得分:0)

它会有所帮助;

$i = 2;
$first_i = $i;
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++;
}
$last_i = $i - 1;
$sumrange = 'D' . $first_i . ':D' . $last_i;
$activeSheet->setCellValue('C' . $i, 'Total:');
$activeSheet->setCellValue('D' . $i, '=SUM(' . $sumrange . ')');