PHPExcel计算公式单元格并格式化货币

PHPExcel calculate formula cell and format currency

现在我正在读取 excel 文件并在 html table 上显示它。
像这样:

 <?php 
 function load_table(){
    require_once('Classes/PHPExcel.php');
    $objReader = PHPExcel_IOFactory::createReader('Excel2007');
    $objReader->setReadDataOnly(true);

    $objPHPExcel = $objReader->load("SampleData.xlsx");
    $objWorksheet = $objPHPExcel->getActiveSheet();
    $highestRow = $objWorksheet->getHighestRow(); // e.g. 10
    $highestColumn = $objWorksheet->getHighestColumn(); // e.g 'F'

    $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn); // e.g. 5

    echo '<table>' . "\n";
    for ($row = 1; $row <= $highestRow; ++$row) {
      echo '<tr>' . "\n";

      for ($col = 0; $col <= $highestColumnIndex; ++$col) {
        echo '<td>';
        echo  $objWorksheet->getCellByColumnAndRow($col, $row)->getValue();     
        echo '</td>' . "\n";

      }

      echo '</tr>' . "\n";
    }
    echo '</table>' . "\n";
}
  ?> 

有时单元格内容是一个公式。我想计算它并 echo 结果(就像 excel 一样)。我尝试了下面的代码,但出现以下错误:
Warning: Illegal string offset 'value' in...

echo  $objWorksheet->getCellByColumnAndRow($col, $row)->getCalculatedValue();  

我也试过类似的东西:

echo  $objWorksheet->getCellByColumnAndRow($col, $row)->getOldCalculatedValue();  

这个有效,但我不想使用 GetOldCalculatedValue 因为:

getOldCalculatedValues() reads the value as it was last calculated by MS Excel (if available) though you can't guarantee it will always be there, or be correct if it is (you can disable autocalculation in MS Excel, or it won't be set if loading a CSV file); while getCalculatedValue() actually recalculates the value within PHPExcel itself.

我还使用 echo 仅打印公式字符串,它看起来很好:

echo $objWorksheet->getCellByColumnAndRow($col, $row)->getValue();  

公式打印:
=F2*E2 =F3*E3 =F4*E4 =F14*E14 ...

那么我怎样才能得到公式的结果并将其格式化为货币呢?

关于单元格格式:

如果您使用

,单元格将没有任何格式
$objReader->setReadDataOnly(true);

因为您专门告诉 PHPExcel 加载单元格格式。如果要读取格式,请不要将 readDataOnly 设置为 true

关于你问题的另一部分,如果你在调用时遇到错误

echo  $objWorksheet->getCellByColumnAndRow($col, $row)->getCalculatedValue();

那么说出公式是什么可能会有用

echo  $objWorksheet->getCellByColumnAndRow($col, $row)->getValue();

应该会告诉您公式,所以也许您可以考虑将其添加到您的问题中,因为了解您是否需要帮助非常有用