'How to set cell as percentage in xls - phpoffice
Hey all I want to set the format of a cell in xls to percentage. I am using phpoffice. the value that I want is 0.04% as percentage. the problem the origin $innervalue is 0.04% as string. this is my code:
if($column == 'E')
{
$innervalue = str_replace('%','',$innervalue); //remove the % sign for float
$innervalue = (float)$innervalue; // set innervalue as float and not string
$sheet->setCellValueExplicit($cell, $innervalue, \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_NUMERIC); //put the inner value as number
$sheet->getStyle($cell)->getNumberFormat()->setFormatCode('#.##%'); // format the cell for 0.04%
}
the problem is that the cell displayed 4.% instead of 0.04%.
if I remove the line
$sheet->getStyle($cell)->getNumberFormat()->setFormatCode('#.##%'); // format the cell for 0.04%
in the xls displayed 0.04 as number, but I need it to display in the xls 0.04% as number
Solution 1:[1]
This is the solution:
Need to get the format from this link https://github.com/PHPOffice/PhpSpreadsheet/blob/master/src/PhpSpreadsheet/Style/NumberFormat.php
if($column == 'E')
{
$sheet->setCellValue($cell, $innervalue); //put the inner value as number
$sheet->getStyle($cell)->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_PERCENTAGE_00);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Bastian |
