python - 如何使用 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))
请帮助,如何实现这一目标
解决方案
简化您的问题,排除 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
推荐阅读
- javascript - 尝试查找成员并接收无法读取未定义错误的属性“获取”
- css - 为什么在 iOS 版 Safari 上的链接上方和外部点击时,css 工具提示不会出现和消失?
- powerbi - Power BI Desktop Pro - 继续进行此更改将删除现有的刷新策略,因为它不再有效
- vue.js - vue-axios:无法读取未定义的属性“帖子”
- c++ - Vulkan-hpp:无法毫无例外地分配命令缓冲区
- python - 使用 ESP32 在 MicroPython 中运行线程时出现问题
- mysql - 虽然“id_genero”确实存在,但错误代码:1072。表中不存在键列“id_genero”出来
- java - 从启用 Checker 框架的构建中创建 Jar?
- reactjs - 如何通过 Jest - Enzyme - Sinon on reactjs + redux + redux thunk 测试 Props 功能
- wordpress - 如何在 wp 中解决这个 forEach 循环问题?