问题
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.
回答1:
assuming your cell is A1 ..
$objPHPExcel->getActiveSheet()->getStyle('A1')
->getNumberFormat()->applyFromArray(
array(
'code' => PHPExcel_Style_NumberFormat::FORMAT_PERCENTAGE_00
)
);
回答2:
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%');
回答3:
You can try this code:
$colLetter = "A";
$rowNumber = "1";
$objPHPExcel->getActiveSheet()
->getStyle("$colLetter:$rowNumber")
->getNumberFormat()
->applyFromArray([
"code" => PHPExcel_Style_NumberFormat::FORMAT_PERCENTAGE
]);
来源:https://stackoverflow.com/questions/16428767/formatting-a-cell-to-a-percentage-in-phpexcel