开发者

Adding percentage in python - xlwt / pyexcelerator

开发者 https://www.devze.com 2023-01-02 06:23 出处:网络
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 t

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.

Rega开发者_C百科rds.


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%'.


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.


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.


Do this

Divide the value by 100 before applying format style '0.00%' to it

style = XFStyle()
style.num_format_str = '0.00%'

new_val = '502.22'
sheet = wb.add_sheet('Sheet1')
sheet.write(num, 1, new_val/100, style)

wb.save('sample.xls')

I hope this helps your purpose.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号