我使用的是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行的数量列计数。
发布于 2020-02-20 08:30:25
在phpspreadsheet中,您可以使用Excel公式。你所需要的就是你想要求和的数字范围。
$SUMRANGE = 'D2:D'.$i;
$activeSheet->setCellValue('D'.$i , '=SUM($SUMRANGE)');
发布于 2019-03-01 07:00:48
你必须拿到第一名:
第一个解决方案:
$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/
发布于 2021-02-28 13:30:49
这将会有所帮助;
$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 . ')');
https://stackoverflow.com/questions/54939336
复制相似问题