2017-02-21 48 views
0

我想從使用openpyxl的列中刪除重複的條目並將唯一條目寫入不同的工作簿。Openpyxl:從列中刪除重複的單元格

輸入文件:

 
Cust1 
Cust1 
Cust1 
Cust2 
Cust2 
Cust3 

預期成果是:

 
Cust1 
Cust2 
Cust3 
wb1 = openpyxl.load_workbook('OldFile.xlsx') 
ws = wb1.active 
wb2 = openpyxl.Workbook() 
ws2 = wb2.active 
k=1 
new_row1 = [] 
for i in range(2, ws.max_row + 1): 
    new_row1.append([])     #list for storing the unique entries 
    row_name = ws.cell(row=i,column=1).value #taking the 1st cell's value 
    new_row1[k].append(row_name)    #Appending the list 
    ws2.append(new_row1)      #writing to new workbook 
    k+=1          
    for j in range(3, ws.max_row + 1): 
    row_name2 = ws.cell(row=j, column=1).value #taking 2nd cell's value 
    if row_name == row_name2:     #comparing both the values 
     i+=1          
     j+=1 
wb2.save('NewFile.xlsx') 

我越來越"IndexError: list index out of range" for line "new_row1[k].append(row_name)",也除了提到的錯誤是有一些必須改變,以獲得要求的輸出。

+0

您需要'k = 0'而不是'k = 1'。 Python中的列表從索引0開始。使用'set()'函數在Python中創建一個唯一的數據列表。你的問題不是Excel問題,而是100%的Python問題。 – Elmex80s

+1

請花一些時間熟悉openpyxl文檔。這是不必要的複雜的代碼。把它分解成容易處理的塊。 –

回答

0

由於@CharlieClark說你的代碼過於複雜。改爲:

ws1 = wb1.active # keep naming convention consistent 

values = [] 
for i in range(2,ws1.max_row+1): 
    if ws1.cell(row=i,column=1).value in values: 
    pass # if already in list do nothing 
    else: 
    values.append(ws1.cell(row=i,column=1).value) 

for value in values: 
    ws2.append([value])