每次循环运行增加一次

每次循环遍历所有表单时,如何让单元格数量增加一个? 我得到它循环通过不同的工作表本身,但我不知道如何将+1添加到单元格值。

for sheet in sheetlist: wsX = wb.get_sheet_by_name('{}'.format(sheet)) ws2['D4'] = wsX['P6'].value 

我试图让['D4']变成D5,D6,D7 ..等自动升级到25。

不需要计数器或笨拙的string转换:openpyxl提供了一个用于编程访问的API。

 for idx, sheet in enumerate(sheetlist, start=4): wsX = wb[sheet] cell = ws2.cell(row=idx, column=16) cell.value = wsX['P6'] 
 for i, sheet in enumerate(sheetlist): wsX = wb.get_sheet_by_name('{}'.format(sheet)) cell_no = 'D' + str(i + 4) ws2[cell_no] = wsX['P6'].value 

把这个写在循环外部:

 x = 'D4' 

在循环中写这个:

 x = x[0] + str(int(x[1:])+1) 

试试这个…这是评论,所以你可以理解它在做什么。

 #counter i = 4 for sheet in sheetlist: #looping from D4 to D25 while i <= 25: wsX = wb.get_sheet_by_name('{}'.format(sheet)) #dynamic way to get the cell cell1 = 'D' + str(i) ws2[cell1] = wsX['P6'].value #incrementing counter i += 1