Openpyxl 1.8.5:使用openpyxl读取在单元格中键入的公式的结果

rav*_*ant 13 python openpyxl

我在其中一张Excel表格中打印了一些公式:

wsOld.cell(row = 1, column = 1).value = "=B3=B4"
Run Code Online (Sandbox Code Playgroud)

但我不能将其结果用于实现其他逻辑,如:

if((wsOld.cell(row=1, column=1).value)='true'):
    # copy the 1st row to another sheet
Run Code Online (Sandbox Code Playgroud)

即使我试图在命令行中打印结果,我最终打印公式:

>>> print(wsOld.cell(row=1, column=1))
>>> =B3=B4
Run Code Online (Sandbox Code Playgroud)

如何在单元格中获得公式的结果而不是公式本身?

Cha*_*ark 20

openpyxl support either the formula or the value of the formula. You can select which using the data_only flag when opening a workbook. However, openpyxl does not and will not calculate the result of a formula. There are libraries out there like pycel which purport to do this.

  • FWIW,如`openpyxl.load_workbook()`中所述,使用`data_only = True`打开工作簿时获得的值是"上次Excel读取工作表时存储的值".这依赖于.xls [x/m/...]文件的缓存功能(除了Microsoft之外,我在其中找到文档). (8认同)

bra*_*ase 10

xlwingsPyXll FlyingKoala、DataNitro 都使用 Excel 作为使用 Python 的界面。

如果您想使用 Python 库,您可以尝试PyCelxlcalculatorFormulasSchedula

我是 xlcalculator 的项目所有者。

xlcalculator 使用 openpyxl 读取 Excel 文件并添加将 Excel 公式转换为 Python 的功能。

将 xlcalculator 与 Excel 文件结合使用的示例:

from xlcalculator import ModelCompiler
from xlcalculator import Model
from xlcalculator import Evaluator

filename = r'use_case_01.xlsm'
compiler = ModelCompiler()
new_model = compiler.read_and_parse_archive(filename)
evaluator = Evaluator(new_model)
val1 = evaluator.evaluate('First!A2')
print("value 'evaluated' for First!A2:", val1)
Run Code Online (Sandbox Code Playgroud)

使用 xlcalculator 和 dict 的示例;

input_dict = {
    "B4": 0.95,
    "B2": 1000,
    "B19": 0.001,
    "B20": 4,
    # B21
    "B22": 1,
    "B23": 2,
    "B24": 3,
    "B25": "=B2*B4",
    "B26": 5,
    "B27": 6,
    "B28": "=B19*B20*B22",
    "C22": "=SUM(B22:B28)",
  }

from xlcalculator import ModelCompiler
from xlcalculator import Model
from xlcalculator import Evaluator

compiler = ModelCompiler()
my_model = compiler.read_and_parse_dict(input_dict)
evaluator = Evaluator(my_model)

for formula in my_model.formulae:
    print("Formula", formula, "evaluates to", evaluator.evaluate(formula))

# cells need a sheet and Sheet1 is default.
evaluator.set_cell_value("Sheet1!B22", 100)
print("Formula B28 now evaluates to", evaluator.evaluate("Sheet1!B28"))
print("Formula C22 now evaluates to", evaluator.evaluate("Sheet1!C22"))
Run Code Online (Sandbox Code Playgroud)


rai*_*ner 5

我已经使用 openpyxl 和 pandas 的组合解决了这个问题:

import pandas as pd
import openpyxl
from openpyxl import Workbook , load_workbook


source_file = "Test.xlsx"
# write to file
wb = load_workbook (source_file)
ws = wb.active
ws.title = "hello world"
ws.append ([10,10])
wb.save(source_file)

# read from file
df = pd.read_excel(source_file)
sum_jan = df ["Jan"].sum() 
print (sum_jan)
Run Code Online (Sandbox Code Playgroud)