Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 11661

OpenPyXL Set Worksheet Formula and Value

$
0
0

I'm trying to create an Excel workbook in Python that includes formulas, and want to parse the workbook later without needing to open it in Excel first to evaluate the formula. E.g., I have a formula with a known computation result, and want to store both the formula and its resulting value using OpenPyXL.

How can I accomplish this with OpenPyXL?

E.g., I want to code the following worksheet:

ValueLog(10)
10 (=LOG10(A2))
101 (=LOG10(A3))

The code I was expecting to write to produce this is something like the following:

import mathfrom openpyxl import Workbook, load_workbookwb = Workbook()ws = wb.activews.cell(1, 1).value = 'Value'ws.cell(1, 2).value = 'Log(10)'for row, i in enumerate([1, 10], start = 2):    ws.cell(row, 1).value = i    formulaCell = ws.cell(row, 2)    # What do I have to assign here in order to be able to read both the formula and value later?    formulaCell.value = math.log10(i)    formulaCell.formula = f'=LOG10(A{row})'wbName = 'test.xlsx'wb.save(wbName)# Read the value and formula back inwb_data     = load_workbook(wbName, data_only = True)wb_formulas = load_workbook(wbName, data_only = False)# The following is expected to print:# 0# =LOG10(A2)print(wb_data['B2'].value)print(wb_formulas['B2'].value)

Viewing all articles
Browse latest Browse all 11661

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>