Adding percentage in python - xlwt / pyexcelerator

非 Y 不嫁゛ 提交于 2019-12-11 13:05:30

问题


just a quick question, how to add percent sign to numbers without modifying number. I have tried format percent with myStyleFont.num_format_str = '0.00%' but it multiplies with 100 but I need just to append percent.

Ty in advance.

Regards.


回答1:


Note carefully: "modifying" and "multiplies with 100" affect the displayed result, they affect neither the value stored in the file nor the value used in formula calculations.

The technique of making an operator be treated as a literal is known as "escaping".

The escape character in Excel number format strings is the backslash.

To do what you want, your format should be r"0.00\%" or "0.00\\%"

The above is a property of Excel, not restricted to Python or xlwt etc. You can test this using one of the UIs (Excel, OpenOffice Calc, Gnumeric).

Note that unless you have a restricted set of users who will read and understand the documentation that you will write [unlikely * 3], you shouldn't do that; it will be rather confusing -- the normal Excel user on seeing 5.00% assumes that the underlying number is 0.05. To see this, in Excel etc type these into A1, A2, A3: 5% then .05 then =A1=A2 ... you will see TRUE in A3.

pyExcelerator is abandonware; why do you mention it???

About myStyleFont.num_format_str = '0.00%' (1) "font" and "num_format_str" are quite independent components of a style aka XF; your variable name "myStyleFont" is confused/confusing. (2) Setting up XFs by poking attributes into objects is old hat in xlwt; use easyxf instead.




回答2:


Just to clarify to anyone, here is an example of formatting a number as a percentage in xlwt:

from xlwt import easyxf, Workbook
wb = Workbook()
ws = wb.add_sheet('Formatting Sheet')
style_percent = easyxf(num_format_str='0.00%')
ws.write(0, 5, 0.12, style_percent)

This shows in the Excel cell as '12.00%'.




回答3:


The 00.0% number format expects percentages, so multiplying by 100 to display it is the correct behavior. To get the results you want, you could either put the data in the cell as a string in whatever format you choose or you could divide by 100.0 before you store the value in the cell.



来源:https://stackoverflow.com/questions/2985678/adding-percentage-in-python-xlwt-pyexcelerator

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