Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python openpyxl data_only=True returning None

I have a simple excel file:

A1 = 200
A2 = 300
A3 = =SUM(A1:A2)

this file works in excel and shows proper value for SUM, but while using openpyxl module for python I cannot get value in data_only=True mode

Python code from shell:

wb = openpyxl.load_workbook('writeFormula.xlsx', data_only = True)
sheet = wb.active
sheet['A3']
<Cell Sheet.A3> # python response
print(sheet['A3'].value)
None # python response

while:

wb2 = openpyxl.load_workbook('writeFormula.xlsx')
sheet2 = wb2.active
sheet2['A3'].value
'=SUM(A1:A2)'  # python response

Any suggestions what am I doing wrong?

like image 740
Michał Nowosielski Avatar asked Mar 20 '16 16:03

Michał Nowosielski


2 Answers

It depends upon the provenance of the file. data_only=True depends upon the value of the formula being cached by an application like Excel. If, however, the file was created by openpyxl or a similar library, then it's probable that the formula was never evaluated and, thus, no cached value is available and openpyxl will report None as the value.

like image 83
Charlie Clark Avatar answered Sep 16 '22 12:09

Charlie Clark


I have replicated the issue with Openpyxl and Python.

I am currently using openpyxl version 2.6.3 and Python 3.7.4. Also I am assuming that you are trying to complete an exercise from ATBSWP by Al Sweigart.

I tried and tested Charlie Clark's answer, considering that Excel may indeed cache values. I opened the spreadsheet in Excel, copied and pasted the formula into the same exact cell, and finally saved the workbook. Upon reopening the workbook in Python with Openpyxl with the data_only=True option, and reading the value of this cell, I saw the proper value, 500, instead of the wrong value, the None type.

I hope this helps.

like image 20
Mohamed Ali Avatar answered Sep 19 '22 12:09

Mohamed Ali