Search code examples
pythonexcelxlwtopenpyxlpyxll

Calculating Excel sheets without opening them (openpyxl or xlwt)


I made a script that opens a .xls file, writes a few new values in it, then saves 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?)


Solution

  • 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:

    XlsxWriter doesn’t calculate the value of a formula and instead stores the value 0 as the formula result. It then sets a global flag in the XLSX file to say that all formulas and functions should be recalculated when the file is opened. This is the method recommended in the Excel documentation and in general it works fine with spreadsheet applications. However, applications that don’t have a facility to calculate formulas, such as Excel Viewer, or some mobile applications will only display the 0 results.

    If required, it is also possible to specify the calculated result of the formula using the options value parameter. This is occasionally necessary when working with non-Excel applications that don’t calculate the value of the formula. The calculated value is added at the end of the argument list:

    worksheet.write_formula('A1', '=2+2', num_format, 4)

    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.