Search code examples
phpexcelcurrency

Show Currency in PHPExcel


I want to format my cells with currency, but I cannot find a way to make It happen. Respectively I'm note really sure where I have to put the code to show the currency behind the values.

I've tried several solutions from the forum but nothing worked.

require_once "Classes/PHPExcel.php";
    $tmpfname = "test.xlsx";
    $excelReader = PHPExcel_IOFactory::createReaderForFile($tmpfname);
    $excelObj = $excelReader->load($tmpfname);
    $worksheet = $excelObj->getSheet(0);
    $lastRow = $worksheet->getHighestRow();




    echo "<table>";
    for ($row = 1; $row <= $lastRow; $row++) {
         echo "<tr><td>";
         echo $worksheet->getCell('A'.$row)->getValue();
         echo "</td><td>";
         echo $worksheet->getCell('B'.$row)->getValue();
         echo "</td><tr>";
    }
    echo "</table>";    

?>


Solution

  • If the cells are already formatted use getFormattedValue instead of getValue when you retrieve them.

    echo $worksheet->getCell('A'.$row)->getFormattedValue();
    echo "</td><td>";
    echo $worksheet->getCell('B'.$row)->getFormattedValue();
    

    If you want to format the raw values from the spreadsheet using your existing code then the PHP number_format function is what you are looking for (in the example below I told it to use 2 decimal places which you may of course change).

    echo number_format($worksheet->getCell('A'.$row)->getFormattedValue(),2);
    echo "</td><td>";
    echo number_format($worksheet->getCell('B'.$row)->getFormattedValue(),2);