NamedFormulaeAndRanges.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. use PhpOffice\PhpSpreadsheet\NamedFormula;
  3. use PhpOffice\PhpSpreadsheet\NamedRange;
  4. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  5. require_once __DIR__ . '/../Header.php';
  6. $spreadsheet = new Spreadsheet();
  7. $worksheet = $spreadsheet->setActiveSheetIndex(0);
  8. // Set up some basic data for a timesheet
  9. $worksheet
  10. ->setCellValue('A1', 'Charge Rate/hour:')
  11. ->setCellValue('B1', '7.50')
  12. ->setCellValue('A3', 'Date')
  13. ->setCellValue('B3', 'Hours')
  14. ->setCellValue('C3', 'Charge');
  15. // Define named ranges
  16. // CHARGE_RATE is an absolute cell reference that always points to cell B1
  17. $spreadsheet->addNamedRange(new NamedRange('CHARGE_RATE', $worksheet, '=$B$1'));
  18. // HOURS_PER_DAY is a relative cell reference that always points to column B, but to a cell in the row where it is used
  19. $spreadsheet->addNamedRange(new NamedRange('HOURS_PER_DAY', $worksheet, '=$B1'));
  20. // Set up the formula for calculating the daily charge
  21. $spreadsheet->addNamedFormula(new NamedFormula('DAILY_CHARGE', null, '=HOURS_PER_DAY*CHARGE_RATE'));
  22. // Set up the formula for calculating the column totals
  23. $spreadsheet->addNamedFormula(new NamedFormula('COLUMN_TOTALS', null, '=SUM(COLUMN_DATA_VALUES)'));
  24. $workHours = [
  25. '2020-0-06' => 7.5,
  26. '2020-0-07' => 7.25,
  27. '2020-0-08' => 6.5,
  28. '2020-0-09' => 7.0,
  29. '2020-0-10' => 5.5,
  30. ];
  31. // Populate the Timesheet
  32. $startRow = 4;
  33. $row = $startRow;
  34. foreach ($workHours as $date => $hours) {
  35. $worksheet
  36. ->setCellValue("A{$row}", $date)
  37. ->setCellValue("B{$row}", $hours)
  38. ->setCellValue("C{$row}", '=DAILY_CHARGE');
  39. ++$row;
  40. }
  41. $endRow = $row - 1;
  42. // COLUMN_TOTAL is another relative cell reference that always points to the same range of rows but to cell in the column where it is used
  43. $spreadsheet->addNamedRange(new NamedRange('COLUMN_DATA_VALUES', $worksheet, "=A\${$startRow}:A\${$endRow}"));
  44. ++$row;
  45. $worksheet
  46. ->setCellValue("B{$row}", '=COLUMN_TOTALS')
  47. ->setCellValue("C{$row}", '=COLUMN_TOTALS');
  48. $helper->log(sprintf(
  49. 'Worked %.2f hours at a rate of %.2f - Charge to the client is %.2f',
  50. $worksheet->getCell("B{$row}")->getCalculatedValue(),
  51. $worksheet->getCell('B1')->getValue(),
  52. $worksheet->getCell("C{$row}")->getCalculatedValue()
  53. ));
  54. $helper->write($spreadsheet, __FILE__, ['Xlsx']);