使用 openpyxl 将公式的值分配给变量

Assigning the value of a formula to a variable with openpyxl

我目前正在学习 Python 以自动创建 excel 文件。 但是,我在 openpyxl 库的条件格式部分遇到了一些麻烦。

这是一段不起作用的代码:

import openpyxl as xl
wb = xl.Workbook()
ws = wb.active
red_color = "ffc7ce"
red_color_font = "9c0103"
red_font = xl.styles.fonts.Font(size=14, bold=True, color=red_color_font)
red_fill = xl.styles.fills.PatternFill(start_color=red_color, end_color=red_color, fill_type="solid")
#------
for i in range(3,131,1):
        ws["B"+str(i)] = "=SUM(C{}:D{})".format(str(i),str(i))
        ws["C"+str(i)] = 0
        ws["D"+str(i)] = 0
        ws["E"+str(i)] = "=SUM(F{}:G{})".format(str(i),str(i))
        ws["F"+str(i)] = 0
        ws["G"+str(i)] = 0
        # conditional formating - putting red cells if second applications have been forgotten
        if i==4:
            threshold = [str(int(ws["B"+str(i-1)].value))]
            ws.conditional_formatting.add("B4",xl.formatting.rule.CellIsRule(operator="lessThan",formula=threshold,fill=red_fill,font=red_font))
        if i>=5:
            threshold = [str(int(ws["B"+str(i-1)].value)-int(ws["B"+str(i-2)].value))]
            ws.conditional_formatting.add("B{}".format(str(i)),xl.formatting.rule.CellIsRule(operator="lessThan",formula=threshold,fill=red_fill,font=red_font))

如您所见,问题来自 threshold 变量。 当我 运行 代码时,我收到以下错误消息:

ValueError: invalid literal for int() with base 10: '=SUM(C3:D3)'

有人知道如何从用于 B 列的公式中提取值吗?

提前致谢!

这取决于excel是否已经打开。在你的例子中,看起来 excel 是由你从 python 生成的,那么 excel.

中没有存储评估值

你能做什么:

一个。由于您在 python 中生成了代码,因此您知道分配给这些单元格的值是什么。您不需要从 excel 读回这些值。您可以创建一个数据框来存储结构,如果您想查看 C[3] 的值,则调用 df['C'].iloc[3]

乙。在尝试访问单元格的评估值之前,您需要打开 excel 并保存它。这样,Mircosoft Excel 将保存有关该单元格的公式和计算值的信息。然后,您可以在 python 代码中读回 excel。更具体地说,您可以读入单元格的公式和值:

wb_values = load_workbook(path_xlsx+wb_name,data_only=True)
wb_formulas = load_workbook(path_xlsx+wb_name)