Formatting a cell to a percentage in PHPExcel

别说谁变了你拦得住时间么 提交于 2019-12-06 17:04:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!