首页 > 解决方案 > 如何使用 xlsxwriter 模块在多个单元格中的 Excel 中动态编写公式?

问题描述

我已经创建了包含一些工作表的 excel 工作簿,并且我添加了一个工作表,我想在该工作表中使用一个公式从另一个工作表中获取值,为此我必须使用 for 循环动态使用公式,但是当我通过 cell2 和cell3 作为我得到的公式中的变量并出现错误:

File "<ipython-input-26-a7cfb4c63c79>", line 8, in <module>
ws2.write_formula(0, 1, '=COUNTIFS(Deviation!%s:%s,"<=-15%")' %(cell2, cell3))

TypeError: not enough arguments for format string`

以下是相关代码:

for cl in range(1, 32):
    cell2 = xl_rowcol_to_cell(1, cl)
    cell3 = xl_rowcol_to_cell(432, cl)
    ws2.write_formula(0, 1, '=COUNTIFS(Deviation!%s:%s,"<=-15%")' %(cell2, cell3))

请帮助,如何实现这一目标

标签: python

解决方案


简化您的问题,排除 excel 内容并单独使用字符串格式打印

cell2 = "A1"
cell3 = "B22"

# TypeError: not enough arguments for format string
print('=COUNTIFS(Deviation!%s:%s,"<=-15%")' %(cell2, cell3))

然后查看文档-您的字符串包含一个'%'文字字符-这使python感到困惑。

该文档告诉您加倍%打印文字:

转换类型是:
[snipp unimportant ones]
'%'-> 不转换任何参数,结果中会产生一个 '%' 字符。

cell2 = "A1"
cell3 = "B22"

formatstr = '=COUNTIFS(Deviation!%s:%s,"<=-15%%")' %(cell2, cell3)
print(formatstr)

# ws2.write_formula(0, 1, formatstr) # use formatted string

瞧。固定的。输出:

=COUNTIFS(Deviation!A1:B22,"<=-15%")

更容易使用str.format或字符串插值(Python 3.x):

print('=COUNTIFS(Deviation!{}:{},"<=-15%%")'.format(cell2, cell3) )
print(f'=COUNTIFS(Deviation!{cell2}:{cell3},"<=-15%%")') # python 3

推荐阅读