你好,我提出了这种解决方案来遍历多行(通过指定行号“ 2”,“ 3”,“ 4”,exc),但是我想在不同的上下文中进行相同的迭代那里有更多的行。 我应该使用什么命令来代替指定行数?
for col in range(3, 4 + 1):
for row in range(2, 14):
Jan = database[str(get_column_letter(col)) + '2'].value
Feb = database[str(get_column_letter(col)) + '3'].value
Mar = database[str(get_column_letter(col)) + '4'].value
Apr = database[str(get_column_letter(col)) + '5'].value
May = database[str(get_column_letter(col)) + '6'].value
Jun = database[str(get_column_letter(col)) + '7'].value
Jul = database[str(get_column_letter(col)) + '8'].value
Aug = database[str(get_column_letter(col)) + '9'].value
Sep = database[str(get_column_letter(col)) + '10'].value
Oct = database[str(get_column_letter(col)) + '11'].value
Nov = database[str(get_column_letter(col)) + '12'].value
Dec = database[str(get_column_letter(col)) + '13'].value
我想要获得的结果是这样的: {'Jan':[218,124],'Feb':[541,874],'Mar':[215,156],'Apr':[365,189],'May':[245,645] ,'Jun':[542,245],'Jul':[542,654],'Aug':[987,354],'Sep':[167,369],'Oct':[367,785] ,“十一月”:[174,412],“十二月”:[841,213]} 考虑Excel上的数据结构:
预先感谢
答案 0 :(得分:1)
是的,正如查理·克拉克(Charlie Clark)所说的,文档中对此进行了介绍。这是我使用openpyxl docs使用的代码:
import openpyxl
from openpyxl.utils import column_index_from_string
from itertools import zip_longest
wb = openpyxl.load_workbook('test.xlsx')
ws = wb.active
col1 = []
col2 = []
col3 = []
elems = []
for (row1,row2,row3) in zip_longest(ws['A1':'A13'],ws['B1':'B13'],ws['C1':'C13']):
for cell1,cell2,cell3 in zip_longest(row1,row2,row3):
col1.append(ws.cell(row=cell1.row,column=column_index_from_string(cell1.column)).value)
col2.append(ws.cell(row=cell2.row,column=column_index_from_string(cell2.column)).value)
col3.append(ws.cell(row=cell3.row,column=column_index_from_string(cell3.column)).value)
for count,elem in enumerate(zip(col1,col2,col3),1):
print(elem)
elems.append(elem)
dict_answer = {x[0]:list(x[1:3]) for x in elems}
print(dict_answer)
请确保将来再阅读文档并搜索以前的查询,然后再问自己的问题