Dum DumDum Dum
Dum DumDum Dum

Reputation: 43

OPENPYXL For loop that goes through each cell in a specified column and replaces its value with an uppercase one

for i in column_d: # column d is a tuple of cell objects in an Excel worksheet   
    if type(i.value) == str: #to avoid empty cells
        print(i.value) #cell value before
        i.value = i.value.upper() # is there a way to shorten this line?
        # without having to write i.value every time
        print(i.value + '\n') # cell value after

Without assigning the cell object to a variable you can change its contents without calling the 'value' but I dont know how I can do it here if I will just reassign a string to the variable i.

<cell_object> = 'text' is the same as <cell_object>.value = 'text'
i = <cell_object>
i = i.value.upper()
type(i) # gives str

Basically Im asking: is there a way to stop repeating i.value so often?

Upvotes: 2

Views: 1180

Answers (1)

Charlie Clark
Charlie Clark

Reputation: 19507

for c in ws['D']:
    if c.data_type == "s" and c.value:
         c.value = c.value.upper()

Inspecting the attribute has a trivial cost

Upvotes: 1

Related Questions