使用openpyx将公式值赋给变量

2024-05-16 23:35:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在学习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变量。 运行代码时,收到以下错误消息:

^{pr2}$

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

提前谢谢!在


Tags: formatthresholdifwsvalueredfillcolor
1条回答
网友
1楼 · 发布于 2024-05-16 23:35:13

这取决于excel是否已打开。在您的例子中,看起来excel是由python生成的,那么excel中没有存储任何计算值。在

你能做什么:

A.因为您是用python生成代码的,所以您知道为这些单元格分配了什么值。您不需要从excel读回这些值。您可以创建一个dataframe来存储结构,如果您想看到C[3]的值,那么调用df['C'].iloc[3]

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

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

相关问题 更多 >