[英]How to write to an excel with multiple worksheets using “xlsxwriter” and not “openpyxl”?
[英]How to write formula dynamically in excel in multiple cells using xlsxwriter module?
我創建了包含一些工作表的 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。
該文檔告訴您將%
加倍以打印文字:
轉換類型有:
[剪掉不重要的]
'%'
-> 不轉換任何參數,結果中包含一個 '%' 字符。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.