openpyxl for循环 – 增加值

我正在尝试使用for循环在Excel表格中设置值,但是我有点卡住了。 它应该设置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))

插值语法应该紧跟在string之后:

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)