How can I see the formulas of an excel spreadsheet in pandas / python?

Question:

I would like to read in an excel spreadsheet to python / pandas, but have the formulae instead of the cell results.

For example, if cell A1 is 25, and cell B1 is =A1, I would like my dataframe to show:

25    =A1

Right now it shows:

25    25

How can I do so?

Asked By: ThrowAway23948238

||

Answers:

OpenPyXL provides this capacity out-of-the-box. See here and here. An example:

from openpyxl import load_workbook
import pandas as pd
wb = load_workbook(filename = 'empty_book.xlsx')
sheet_names = wb.get_sheet_names()
name = sheet_names[0]
sheet_ranges = wb[name]
df = pd.DataFrame(sheet_ranges.values)
Answered By: Aleksey Bilogur

Yes, it is possible. I recently found a package that solves this issue in a quite sophisticated way. It is called portable-spreadsheet (available via pip install portable-spreadsheet). It basically encapsulates xlsxwriter. Here is a simple example:

import portable_spreadsheet as ps
sheet = ps.Spreadsheet.create_new_sheet(5, 5)
# Set values
sheet.iloc[0, 0] = 25  # Set A1
sheet.iloc[1, 0] = sheet.iloc[0, 0]  # reference to A1
# Export to Excel
sheet.to_excel('output/sample.xlsx')

It works in a similar way as Pandas Dataframe.

Answered By: Emma Brown

There is one option to do this using xlwings and pandas modules.
xlwings provides a way to automate the excel via python scripts.

Create one "sample.xlsx" file and add random formula in range("A1").

Below is the sample code which will read the value as well as the formula from the given file:

import pandas as pd
import xlwings as xw

wbk = xw.Book('sample.xlsx')
ws = wbk.sheets[0]
print(ws.cells(1,1).value)
print(ws.cells(1,1).formula)

Same thing applies on range as well. You can assign the range.value into dataframe and vice versa.
In case you want to get formulas from big range, you can get that too, but it will return tuple.

Hope this is helpful at some extent.

Answered By: Hemz

Use xlwings. This is a very useful tool in Python, it has detailed documentation and videos. Good luck!

Answered By: Aruparna Maity