2016-09-27 43 views
0

我想檢查現有電子表格中的名稱列,如果存在,我想用該行的時間戳更新特定列。我很尷尬,因爲我無法弄清楚如何通過一個for循環來解決這個問題。 for循環將追加更多的行爲它不匹配的行,當我嘗試在與行匹配名稱後對其進行戳記時,列中不顯示任何內容。問:OpenPyxl檢查現有行,然後更新單元格

for rowNum in range(2, ws1.max_row): 
     log_name = ws1.cell(row=rowNum,column=1).value 
     if log_name == chkout_new_name_text: 
      print 'apple' + 'pen' 
      ws1.cell(row=rowNum, column=2).value = str(time.strftime("%m/%d/%y %H:%M %p")) 
      break 
     else: 
      continue 
      print 'pen' + 'pineapple' 
      # Normal procedure 

任何幫助將不勝感激。

+0

這有什麼錯用'for'循環? –

+0

當我使用for循環時,它爲範圍2到max_row中的每個int執行else語句。我試圖放棄if語句,但它仍然繼續。有沒有辦法告訴循環在第一次成功後停止所有循環? –

+0

我還有一個問題,如果在範圍內(2,ws1.max_row)rowNum:最大行返回適量的行,但for循環不處理最後一個數字。是否有一個原因?是範圍這個錯誤的選擇? –

回答

0

想通了

name_text = raw_input("Please enter name: ") 
    matching_row_nbr = None 
    for rowNum in range(2, ws1.max_row + 1): 
     log_name = ws1.cell(row=rowNum,column=1).value 
     if log_name == name_text: 
      # Checks for a matching row and remembers the row number 
      matching_row_nbr = rowNum 
      break 
    if matching_row_nbr is not None: 
     # Uses the matching row number to change the cell value of the specific row 
     ws1.cell(row=matching_row_nbr, column=6).value = str(time.strftime("%m/%d/%y %H:%M - %p")) 
     wb.save(filename = active_workbook) 
    else: 
     # If the none of the rows match then continue with intended use of new data 
     print name_text