php 将单元格格式化为 PHPExcel 中的百分比

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16428767/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 11:07:06  来源:igfitidea点击:

Formatting a cell to a percentage in PHPExcel

phpformattingphpexcelpercentage

提问by cwiggo

I am automating an excel spreadsheet using PHP.

我正在使用 PHP 自动化 Excel 电子表格。

I have been looking for a way to pragmatically format a cell to a percentage in PHPExcel.

我一直在寻找一种在 PHPExcel 中将单元格格式化为百分比的方法。

I want to change a value like

我想改变一个像

0.077922078

0.077922078

to

8%

8%

Is there a solution for this?

有解决方案吗?

Thanks in advance.

提前致谢。

回答by

assuming your cell is A1 ..

假设您的单元格是 A1 ..

$objPHPExcel->getActiveSheet()->getStyle('A1')
    ->getNumberFormat()->applyFromArray( 
        array( 
            'code' => PHPExcel_Style_NumberFormat::FORMAT_PERCENTAGE_00
        )
    );

回答by lubosdz

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:

PHPExcel 库只预定义了几个基本的格式化常量。您实际上可以出于任何目的(着色、格式化小数和千位等)构建自己的。Excel 中的格式化功能非常强大。以下将使用 3 个小数位格式化百分比并将负值着色为红色:

$workSheet
    ->getStyleByColumnAndRow($column, $row)
    ->getNumberFormat()
    ->setFormatCode('0.000%;[Red]-0.000%');

回答by simhumileco

You can try this code:

你可以试试这个代码:

$colLetter = "A";
$rowNumber = "1";

$objPHPExcel->getActiveSheet()
    ->getStyle("$colLetter:$rowNumber")
    ->getNumberFormat()
    ->applyFromArray([
        "code" => PHPExcel_Style_NumberFormat::FORMAT_PERCENTAGE
    ]);