You write a formula with openpyxl, save the file and read it back. Instead of
the result, you get the formula text or None:
import openpyxl
book = openpyxl.Workbook()
sheet = book.active
sheet["A1"] = 10
sheet["A2"] = 32
sheet["A3"] = "=SUM(A1:A2)"
book.save("report.xlsx")
print(openpyxl.load_workbook("report.xlsx").active["A3"].value)
# =SUM(A1:A2)
print(openpyxl.load_workbook("report.xlsx", data_only=True).active["A3"].value)
# None
Why it happens
An XLSX file stores each formula and, next to it, the last result. Excel calculates that result and saves it. openpyxl does not calculate formulas.
- Without
data_only, openpyxl returns the formula text. - With
data_only=True, openpyxl returns the stored result. - A file that openpyxl wrote has no stored results, so
data_only=TruereturnsNone.
A file from Excel has stored results. If you change a cell with openpyxl and save, the stored results of dependent formulas stay old.
pandas reads the stored results too. For the file above,
pandas.read_excel("report.xlsx", header=None) returns only two rows. The
formula row has no value, so pandas drops it.
Fix 1: Calculate in Excel
Open the file in Excel and save it. Excel calculates every formula and stores the results. This works for one file. For many files, you need Excel on the machine and a script that controls it.
Fix 2: Calculate with pycel
pycel calculates formulas in Python. It reads the file and returns the value of one cell:
from pycel import ExcelCompiler
excel = ExcelCompiler(filename="report.xlsx")
print(excel.evaluate("Sheet!A3"))
# 42
Use pycel when you need a few values in Python. The file itself stays unchanged.
Fix 3: Calculate with formulas
The formulas package calculates a whole workbook:
import formulas
model = formulas.ExcelModel().loads("report.xlsx").finish()
solution = model.calculate()
solution maps each cell, such as '[report.xlsx]SHEET'!A3, to its value.
Fix 4: Calculate when you save, with CrabXL
CrabXL uses the openpyxl interface. Its save can
calculate every formula first and store the results in the file:
import crabxl as openpyxl
book = openpyxl.Workbook()
sheet = book.active
sheet["A1"] = 10
sheet["A2"] = 32
sheet["A3"] = "=SUM(A1:A2)"
book.save("report.xlsx", calculate=True)
Now every reader sees the result. openpyxl with data_only=True returns
42.0, and pandas returns all three rows. This also works for a file you open
and edit:
book = openpyxl.load_workbook("input.xlsx")
book.active["A1"] = 100
book.save("output.xlsx", calculate=True)
CrabXL calculates with the Formualizer
engine. It does not calculate array formulas and data tables. Install it with
pip install crabxl.
Which fix to use
- For one file, open and save it in Excel.
- To get a few values in Python, use pycel or formulas.
- To produce files that other programs read correctly, save with CrabXL and
calculate=True.