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

标签 php excel phpspreadsheet phpoffice

我正在使用 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 行的数量列数。

最佳答案

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

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

关于php - 如何在php phpspreadsheet中使用excel sum公式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54939336/

相关文章:

php - 将mysql的连接和查询重写为PDO

Laravel - 下载 PhpSpreadsheet 之前不保存

phpspreadsheet - 如何使用 phpspreadsheet 绘制或实现饼图?

PHP - 执行我的 sql 查询时出现问题

php - 更改后刷新页面而不重置搜索查询

php - 将请求保存到数据库

Excel 公式仅显示公式,而不显示 Office 2010 中单元格内的值

vba - 将工作表单元格的值分配给常量

excel - C# WinUI 3 我无法使用 FileSavePicker 对话框中指定的文件来创建 Excel 报告文件

php - 使用 PhpSpreadsheet 编写 xlsx 文件会删除所有文本框