I am automating an excel spreadsheet using PHP.
I have been looking for a way to pragmatically format a cell to a percentage in PHPExcel.
I want to change a value like
0.077922078
to
8%
Is there a solution for this?
Thanks in advance.
I am automating an excel spreadsheet using PHP.
I have been looking for a way to pragmatically format a cell to a percentage in PHPExcel.
I want to change a value like
0.077922078
to
8%
Is there a solution for this?
Thanks in advance.
assuming your cell is A1 ..
$objPHPExcel->getActiveSheet()->getStyle('A1')
->getNumberFormat()->applyFromArray(
array(
'code' => PHPExcel_Style_NumberFormat::FORMAT_PERCENTAGE_00
)
);
_00
is the key!!! I tried it and it works like charm! Thank you @Chris –
Hairspring PHPExcel library has predefined only few basic formatting constants. You can actually build your own for virtually any purpose (coloring, formatting decimals & thousands etc). Formatting capabilities in Excel are huge. Following will format percent with 3 decimal places and coloring negative values to red:
$workSheet
->getStyleByColumnAndRow($column, $row)
->getNumberFormat()
->setFormatCode('0.000%;[Red]-0.000%');
You can try this code:
$colLetter = "A";
$rowNumber = "1";
$objPHPExcel->getActiveSheet()
->getStyle("$colLetter:$rowNumber")
->getNumberFormat()
->applyFromArray([
"code" => PHPExcel_Style_NumberFormat::FORMAT_PERCENTAGE
]);
Just in case someone else is seeing this after PHPExcel turns to PHPSpreadsheet.
PHPSpreadsheet have a dedicated function to apply format codes. So, to set a number as percentage now we need to replace applyFromArray()
to setFormatCode()
as follow:
$spreadsheet
->getActiveSheet()
->getStyle("A1")
->getNumberFormat()
->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_PERCENTAGE_00);
Note: setFormatCode()
seems to not support to apply to a entire column/row. So, if it is your case, you will need to create a loop over column/row to apply for each cell individually.
© 2022 - 2024 — McMap. All rights reserved.