简体   繁体   中英

Read cell value, NOT the formula in Excel sheet using Python

I am trying to read only the cell value in an Excel spread sheet using Python's openpyxl , but I am only able to read the forumulas.

I have already come across countless questions on Stack Overflow that ask this question and they all says to set the flag data_only=True like this:

wb = openpyxl.load_workbook(reference_filename, data_only=True)
ws = wb.worksheets[0]

cell_value = ws.cell(7, 1).value
print(cell_value)

However, this is still only printing the formula.. Why??

I just need the value that is in the cell.

The openpyxl documentation ( https://openpyxl.readthedocs.io/en/latest/usage.html?#read-an-existing-workbook ) notes that...

data_only controls whether cells with formulae have either the formula (default) or the value stored the last time Excel read the sheet.

If the worksheet hasn't been opened by Excel previously, it may not have the last-calculated values stored and therefore openpyxl may not be able to extract it.

Do you have to use openpyxl?

Check this out using pandas:

ws = pd.read_excel('try.xlsx', sheet_name=0, header=None)
cell_value = ws[7][1]
print(cell_value)

For me this gives the result not the formula.

The problem could be on the excel file. If the cell you are trying to read is set as 'Show formula', then the openpyxl will read the formula instead of the value. Go to your excel and Formulas -> Formula Auditing -> Uncheck Show Formulas save the file and run the python program again

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM