问:OpenPyxl检查现有行,然后更新单元格

时间:2016-09-27 18:30:02

标签: python openpyxl

我想检查现有电子表格中的名称列,如果存在,我想更新具有该行时间戳的特定列。我已经陷入了困境,因为我无法通过for循环来弄清楚如何解决这个问题。 for循环将为它没有匹配的那些追加更多的行,当我在将名称与行匹配后尝试标记时,没有任何内容显示在列中。

    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

非常感谢任何帮助。

1 个答案:

答案 0 :(得分: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