Как использовать формулу суммы Excel в php phpspreadsheet? - PullRequest
0 голосов
/ 01 марта 2019

Я использую библиотеку 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 строк количества столбцов.

1 Ответ

0 голосов
/ 01 марта 2019

Вы должны принять всего 1:

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

2-е решение:

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

Я был отослать: https://phpspreadsheet.readthedocs.io/en/stable/topics/calculation-engine/

...