Michael
Michael

Reputation: 41

Openpyxl read 100% as 'int'

I'm trying to read an excel file using Openpyxl:

cell A1: 100%

cell A2: 89.3%

both of them are in percentage format in excel.

but when I read them in Openpyxl, it gets:

>>> type(ws['A1'].value)
<class 'int'>
>>> type(ws['A2'].value)
<class 'float'>

Is there a way to read the cell format of cell A1 as 'percentage', or just read it as float '1.00'?

I don't want to add a judgment in my code like 'value==1' or anything.

Upvotes: 1

Views: 1239

Answers (3)

Michael
Michael

Reputation: 41

I found my solution when I posted my question half an hour ago ...

just check

cell.number_format

Example:

value = ws.cell(i, j).value
nf = ws.cell(i, j).number_format
if value == 1 and (nf =='0.0%' or nf == '0.00%'):
    value = '100%'

Upvotes: 3

Giorgos Kavalieratos
Giorgos Kavalieratos

Reputation: 465

You could return something like

res = f"{value * 100}%"

so the 1.00 would be "100%"

Upvotes: 1

Aiden-exe
Aiden-exe

Reputation: 14

My first guess would be to use a method to remove all the % signs in the cella and store that to a new variable and convert that to an integer and then divide by 100 to get a floating point/integer number. It's a bit of a weird way to do it though.

Upvotes: -1

Related Questions