NPV.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. <?php
  2. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  3. require __DIR__ . '/../../Header.php';
  4. $helper->log('Returns the Net Present Value of an investment, based on a supplied discount rate,');
  5. $helper->log('and a series of future payments and income.');
  6. // Create new PhpSpreadsheet object
  7. $spreadsheet = new Spreadsheet();
  8. $worksheet = $spreadsheet->getActiveSheet();
  9. // Add some data
  10. $arguments = [
  11. ['Annual Discount Rate', 0.02, 0.05],
  12. ['Initial Investment Cost', -5000.00, -10000],
  13. ['Return from Year 1', 800.00, 2000.00],
  14. ['Return from Year 2', 950.00, 2400.00],
  15. ['Return from Year 3', 1080.00, 2900.00],
  16. ['Return from Year 4', 1220.00, 3500.00],
  17. ['Return from Year 5', 1500.00, 4100.00],
  18. ];
  19. // Some basic formatting for the data
  20. $worksheet->fromArray($arguments, null, 'A1');
  21. $worksheet->getStyle('B1:C1')->getNumberFormat()->setFormatCode('0.00%');
  22. $worksheet->getStyle('B2:C7')->getNumberFormat()->setFormatCode('$#,##0.00');
  23. // Now the formula
  24. // When initial investment is made at the end of the first period
  25. $worksheet->setCellValue('B10', '=NPV(B1, B2:B7)');
  26. $worksheet->getStyle('B10')->getNumberFormat()->setFormatCode('$#,##0.00');
  27. $helper->log($worksheet->getCell('B10')->getValue());
  28. $helper->log('NPV() Result is ' . $worksheet->getCell('B10')->getFormattedValue());
  29. // When initial investment is made at the start of the first period
  30. $worksheet->setCellValue('C10', '=NPV(C1, C3:C7) + C2');
  31. $worksheet->getStyle('C10')->getNumberFormat()->setFormatCode('$#,##0.00');
  32. $helper->log($worksheet->getCell('C10')->getValue());
  33. $helper->log('NPV() Result is ' . $worksheet->getCell('C10')->getFormattedValue());