2015-12-08 30 views
0

我有列表的字典:Openpyxl:从字典追加列表结束匹配的excel行

dictofannotations = { 
'5988': ['1', '1', '1', '1', '1', '1', '1', '2', '1'], 
'5989': ['2', '1', '1', '1', '1', '1', '1', '1', '1'], 
'5982': ['1', '1', '2', '1', '1', '1', '1', '2', '1'] 
} 

这些字典键可以在Excel文件中的一个柱(9或J)的发现。当找到字典键的excel文档中的匹配项时,我想将列表(一个列表项目添加到一个单元格)追加到匹配行的末尾。

我很近,但无法写入工作簿。

filename = 'dataset.xlsx' 
wb = load_workbook(filename) 
ws = wb.get_sheet_by_name('Dataset') 


for x in range(1,7582): 
##7582 is the number of rows in the document, 1 should ignore the header 

    if ws.cell(row = x, column = 9).value in dictofannotations: 
     ws.append(dictofannotations[ws.cell(row = x, column = 9)]) 

wb.save("finaldataset.withannotations.xlsx") 

回答

0

行对于openpyxl物理上不存在,因此您不能将单元格追加到现有工作表。相反,您必须手动创建/覆盖单元格。

这个逻辑是这样的:

if cell in dictofannotations: 
    values = dictofannotations[key] 
    for idx, value in values: 
      ws.cell(row=x, col=9+idx, value=value)