简体   繁体   中英

Python/ Openpyxl: How to pass a list to an if statement and make the cells bold if they contain any strings from the list value (MacOS)

I'm trying to make cells in column A bold if they contain any of the words in words(list) the code executes but nothing is happening in my final cells.

I've been styling the workbook with Openpyxl.

My code:

header_style = Font(bold = True)    
A = ws['A1':'A44']
words =  ['Assets', 'Current Assets', 'Liabilities' , 'Equity']
for words in A:    
     if cell.value == words:
            cell.font = header_style

Any help would be greatly appreciated!

Many thanks!

I tested on my side and here are the changes I made:

header_style = Font(bold = True)    
words =  ['Assets', 'Current Assets', 'Liabilities' , 'Equity']

wb = load_workbook(filename = 'test.xlsx')
ws = wb.active

# Get each cell of column A
for cell in ws['A']: 
    if cell.value in words:
            cell.font = header_style

wb.save('test.xlsx') // do not forget to save the file again

if cell.value == words: to if cell.value in words:

This don't check if value is in the words array. you have to replace == to in

And don't forget to save the file again with wb.save('test.xlsx')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM