openpyxl for loop - 增加值

openpyxl for loop - increment the value

我正在尝试使用 for 循环在 excel sheet 中设置值,但我有点卡住了。它应该将 A1 - A4 设置为列表中的项目。当我尝试在 for 循环中递增 A1 时,我的代码返回错误:

import openpyxl

wb = openpyxl.load_workbook('morning.xlsx')
am_sheet = wb.active

list1 = ['dog', 'cat', 'bear', 'mouse']

i = 1

for x in list1:
    am_sheet['%s'].value = x % ("A" + str(i))
    i += 1

错误反击:

Traceback (most recent call last):
  File "C:/Python27/Pyjects/am/twinder.py", line 11, in <module>
   am_sheet['%s'].value = x % ("A" + str(i))
TypeError: not all arguments converted during string formatting

有什么想法吗?

am_sheet['%s'].value = x % ("A" + str(i))

插值语法应紧跟在字符串文字之后:

am_sheet['%s' % ("A" + str(i))].value = x

但你可以使用更清洁的 .format:

am_sheet['A{}'.format(i)].value = x

不要在任何代码中使用 ws['A%s' % (i)]。改用工作表的 .cell() 方法:ws.cell(row=i, column=1)