Search code examples
pythonxlwtpyexcelerator

Adding percentage in python - xlwt / pyexcelerator


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.


Solution

  • 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.