Edward N. Edward N. - 11 months ago 74
Python Question

Q: OpenPyxl checking for existing row and then updating cell

I want to check for a name column in an existing spreadsheet and if it exists I want to update a specific column with a time stamp for that row. I'm in a rut because I can't figure out how to go about this with out a for loop. The for loop will append more rows for the ones it didnt match and nothing shows up in column when I try to stamp it after matching a name with a row.

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"))
print 'pen' + 'pineapple'
# Normal procedure

Any help will be greatly appreciated.

Answer Source

Figured it out

    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
    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)
        # If the none of the rows match then continue with intended use of new data
        print name_text