Search code examples
pythonopenpyxl

openpyxl for Conditioned Formatting of an Excel File


Brand new to openpyxl and the program abstraction of what I am writing is this: There is a list of street names in Excel. The user should be able to input: a street name to search for in one column, a string to input in a separate column, and which column the string should be input to. If a match with street is found in column A, day is inserted in the adjacent cell in column add_to_col.

Here is my code so far:

#Necessary imports for xlsx files
import openpyxl as xl

#Import file
wb = xl.load_workbook('test.xlsx')
ws = wb.active

#Initialize values for openpyxl use
sheet = wb['Sheet1']

#Accept user input
street = input("Street name: ")
day = input("Day to append: ")
add_to_col = int(input("Column to add value to: "))

#Initialize values for loop use
row = 2
column = add_to_col
mycell = sheet['A2']

#Iterate through column and return corresponding day in adjacent row
for i in range(row,6300):
    
    if mycell.value == street:
        cellref = sheet.cell(row=i, column=column)
        mycell.value == day

#Save workbook
wb.save("test.xlsx")

From my understanding, openpyxl reads columns as characters rather than ints, so I'm running into a type error when cellref = sheet.cell(row=i, column=column) is executed.

How can I implement this for either A. openpyxl to recognize columns as characters or B. take a different approach to add values to an adjacent cell when a match for street is found?


Solution

  • I've always referenced cells by the column number as below:

    ws.cell(row=10,column=3).value =
    

    But remember, column indexes are 0 based.