Skip to main content
 首页 » 编程设计

python之如何使用 xlsxwriter 模块在多个单元格的 excel 中动态编写公式

2024年11月01日10hnrainll

我创建了包含一些工作表的 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)) 

求助,如何实现

请您参考如下方法:

简化您的问题,简化 excel 内容并单独使用 print 字符串格式:

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

然后查看the documentation - 你的字符串包含一个 '%' 作为文字字符 - 这会混淆 python。

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

The conversion types are:
[snipp unimportant ones]
'%' -> No argument is converted, results in a '%' character in the result.

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