openpyxl Returns None for Formula Cells
openpyxl does not calculate formulas. With data_only=True it reads the value cached in the file, and only a program that calculates writes that cache. A workbook saved by openpyxl therefore has formulas but no cached values, and every formula cell reads back as None.
Recalculating the file with Formulon fills in the cache. Formulas stay in place, and openpyxl reads the values afterwards. Excel does not have to be installed.
Recalculate, then read
pip install formulon openpyxlfrom pathlib import Path
from formulon import CalcMode, Workbook
# input.xlsx stands for the report openpyxl wrote: formulas in it, C1 holds =A1+B1.
path = Path("input.xlsx")
with Workbook.load(path) as book:
book.set_profile_id("win-365-en_US")
book.save(path)
with Workbook.load(path) as stored:
# Manual mode reads the values stored in the file, which is what openpyxl sees.
stored.set_calc_mode(CalcMode.MANUAL)
print(stored["Sheet1"]["C1"]) # 30.0Loading a file marks its formulas dirty, so the first read or save() recomputes them, and the saved file carries the results as cached values. The second block reloads the file in manual mode, which returns the stored values without recalculating. That is the view load_workbook(path, data_only=True) has: sheet["C1"].value is 30.0 instead of None. load_workbook(path) without data_only still returns the formula, so the file can go back into the same openpyxl pipeline.
Things to know
- Recalculate last. Formulon writes the values it holds when
save()runs, after recomputing anything dirty. If openpyxl edits and saves the file after that, the cache is gone again. - Pick a profile. Text formats, decimal separators and some text functions depend on the Excel locale. The profile is not saved in the file, so call
set_profile_idafter every load. See Locale profiles. - Pin the clock for dates.
NOW()andTODAY()read the current time. Callset_pinned_now(datetime.datetime(...))before reading or saving when the output must be reproducible. - Check what your workbook uses. Function coverage and the parts of
.xlsxthat survive a save are listed in Formula coverage and File format support.
Related
- Recalculate .xlsx files in Python: setting inputs and validating results in a batch job.
- Python API: every
WorkbookandSheetmethod.