2015-12-08 29 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)