I made a script that opens a xls. file, writes a few new value's in it, then save the file.
Later the script opens it again, and wants to find the answers in some cells which contain formulas.
If I call that cell with openpyxl, I get the formula (ie: =A1*B1). And if I activate data_only, i get nothing.
Is there a way to let python calculate the xls file? (or should I try PyXll?)
There is actually a project that takes Excel formulas and evaluates them using Python: Pycel.
Pycel uses Excel itself (via COM) to extract the formulas, so in your case you would skip that part.The project probably has something useful that you can use, but I can't vouch for its maturity or completeness. It was not really developed for the general public.There is also a newer project called Koala which builds on both Pycel and OpenPyXL.
Another approach, if you can't use Excel but you can calculate the results of the formulas yourself (in your Python code), is to write both the value and the formula into a cell (so that when you read the file, you can just pull the value, and not worry about the formula at all). As of this writing, I haven't found a way to do it in OpenPyXL, but XlsxWriter can do it. From the documentation:
With this approach, when it's time to read the value, you would use OpenPyXL's
data_only
option. (For other people reading this answer: If you use xlrd, then only the value is available anyway.)Finally, if you do have Excel, then perhaps the most straightforward and reliable thing you can do is automate the opening and resaving of your file in Excel (so that it will calculate and write the values of the formulas for you). xlwings is an easy way to do this from either Windows or Mac.
I realize this question is old, but I ran into the same problem and extensive searching didn't produce an answer.
The solution is in fact quite simple so I will post it here for posterity.
Let's assume you have an xlsx file that you have modified with
openpyxl
. As Charlie Clark mentionedopenpyxl
will not calculate the formulas, but if you were to open the file in excel the formulas would be automatically calculated. So all you need to do is open the file and then save it using excel.To do this you can use the
win32com
module.That's it. I've seen all these suggestions to use Pycel or Koala, but that seems like a bit of overkill if all you need to do is tell excel to open and save.
Granted this solution is only for windows.
No, and in
openpyxl
there will never be. I think there is a Python library that purports to implements an engine for such formualae which you can use.