Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

openpyxl formatting cell with decimal

i am trying to set cell format to display 2 decimals, i need it to show 2 decimals, somehow when i use different office application to open, it gives mixed results, i am new to openpyxl (using latest 2.5.1), i have go through the documentation, setting the format seems pretty straight forward

what i have done for setting format is:-

ws.column_dimensions['F'].number_format = '#,##0.00'
ws.column_dimensions['G'].number_format = '#,##0.00'

not too sure am i miss out any?

For the attached image, it shows Open Office and Libre Office able to show the two decimals i needed, somehow WPS and MS Excel unable to show two decimals, a quick check on all the above format cell (through right click on that cell), Open Office and Libre Office is in Number format, somehow WPS and MS Excel is in General format

note: i have tried setting more decimals, e.g.: 3 decimals or more, still Open Office and Libre showing the specified decimals without problem, but WPS and MS Excel dont

enter image description here

like image 648
hghew Avatar asked Jan 29 '23 10:01

hghew


2 Answers

i have found a work around, which i need to set every single cell manually for formatting it to two decimals, seems working when using WPS and MS Excel to open

for row in range(1, rows):
    ws["F{}".format(row)].number_format = '#,##0.00'
    ws["G{}".format(row)].number_format = '#,##0.00'
like image 160
hghew Avatar answered Jan 31 '23 00:01

hghew


After doing the suggested, it still did not work for me. Seems like MS Excel still sees the cell value as String.

So I tried to do a manual conversion of each cell before formatting:

for row in range(1, rows):
    ws["F{}".format(row)].value = float(ws["F{}".format(row)].value)
    ws["F{}".format(row)].number_format = '#,##0.00'

Gladly, it worked. I'm using Python 2.7.6. MS Excel Version 1808 64 bit.

like image 23
elpa Avatar answered Jan 30 '23 23:01

elpa