16

I need to display two decimal places in Excel (xlsx). I'm using PHPExcel. In PHP, I can use something like the following to display only the specified number of decimal paces.

echo sprintf("%0.2f", $row['price']);

which always displays two decimal places even though the value contains no decimal point i.e if the value of $row['price'] is 1500, it will echo 1500.00. I need to write the same value to excel. I tried

$sheet->setCellValue("A1", sprintf("%0.2f", $row['price']));

but it displays 1500 instead of displaying 1500.00 (because Excel automatically assumes it to be a numeric value and the part after the decimal point i.e .00 in this case is truncated).

I also tried the following

$sheet->getStyle("A1")->getNumberFormat()->setFormatCode('0.00');

but it's not sufficient to achieve what is specified.

How can I (always) display the specified number of decimal places in Excel using PHPExcel?

pnuts
  • 58,317
  • 11
  • 87
  • 139
Tiny
  • 27,221
  • 105
  • 339
  • 599

6 Answers6

34
$sheet->getStyle("A1")->getNumberFormat()->setFormatCode('0.00'); 

should work, as long as the value in cell A1 is a number and not a formatted string... don't try to force Excel formatting by using sprintf, simply use the format codes.

Mark Baker
  • 209,507
  • 32
  • 346
  • 385
  • is it ok to use setFormatCode('###,###,###,##0.00'); to add commas to the mix or there a better way? – chris Oct 13 '13 at 06:20
  • 1
    It's perfectly valid to us setFormatCode('#,##0.00'); to indicate using a thousands separator - or pretty much any format code that MS Excel itself uses – Mark Baker Oct 13 '13 at 06:55
5

Formatted as number with comma. Assuming that value is not exceeded by 9 digits.

$sheet->getStyle("A1")->getNumberFormat()->setFormatCode('###,###,###.##');
Tiny
  • 27,221
  • 105
  • 339
  • 599
4

You can also do this:

$sheet->setCellValue("A1",sprintf("%0.2f",$row['price']),true)->getStyle()->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_NUMBER_00);

Adding 'true' at setCellValue, you refer directly to the cell instead of the worksheet and you can call the getStyle method without the cell value.

Petter Friberg
  • 21,252
  • 9
  • 60
  • 109
Ichigo79
  • 41
  • 2
3

If you want some special characters just use html_entity_decode:

$currencyFormat = html_entity_decode("€ 0,0.00",ENT_QUOTES,'UTF-8');
$objPHPExcel->getActiveSheet()
            ->getStyle("A1")
            ->getNumberFormat()->setFormatCode($currencyFormat);
Bruno
  • 71
  • 2
3
$objPHPExcel->getActiveSheet()->getStyle('ce')->getNumberFormat()->setFormatCode('0.00');
Christian
  • 27,509
  • 17
  • 111
  • 155
Lavanya
  • 31
  • 1
2

Try that:

$sheet->getStyle("A1")->getNumberFormat()->setFormatCode('### ### ### ##0.00');

it works.

simhumileco
  • 31,877
  • 16
  • 137
  • 115