Search code examples
formattingphpexcelnumber-formatting

How to format a percentage number as Excel percentage using PHPExcel?


In PHP, I have floating point numbers such as $number = 1.91.

I want to format them in an Excel sheet using PHPExcel as 1.91% (percentage format, not string format). How do I do this?

I tried:

$sheet->getCell($colID.$rowID)->setValue($number)->getStyle()->getNumberFormat()->setFormatCode('#,##0.00%');

But then the number gets formatted as 191%. Is the only solution to divide $number by 100 first?


Solution

  • If you set 0.5 in a cell, and format it as a percentage, then it will appear as 50%. if you store 50 in a cell, and format it as a percentage, then it will appear as 5000% that is how it should be. I suggest dividing by 100

    setCellValue('A1', 1.91/100)
    

    and following will format percent with 2 decimal:

    $sheet->getActiveSheet()->getStyle($colID.$rowID)->getNumberFormat()->setFormatCode('0.00%');