5

我正在使用 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;

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

4

3 回答 3

5

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

$SUMRANGE = 'D2:D'.$i;
$activeSheet->setCellValue('D'.$i , '=SUM($SUMRANGE)');
于 2020-02-20T08:30:24.500 回答
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);

第二种解决方案:

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

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

于 2019-03-01T07:00:48.193 回答
1

我会帮你的;

$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 . ')');
于 2021-02-28T13:30:49.310 回答