简体   繁体   中英

Python/ Openpyxl: Formatting a row across multiple columns based on criteria

I'm using openpyxl and I would like to format the borders across a row if column A is in my words list.

My Code:

header_style = Font(bold = True)

gone = Side(border_style = 'none')
thick = Side(border_style = 'thick')
thin = Side(border_style = 'thin')

tb_border = openpyxl.styles.borders.Border(
            left = gone,
            right = gone,
            top = thin,
            bottom = thick)


A = ws['A1':'A44']
words =  ['Assets', 'Current Assets', 'Liabilities']
    for cell in ws['A']:
        if cell.value in words:
            cell.font = header_style
            cell.border = tb_border

So far, this only makes column A bold and with borders. I would like the cell.font & border to work across the row covering columns A - E.

I also tried,

  for row in rows:
            if cell.value in words:
                cell.border = tb_border
                cell.font = header_style

But again, this just did the cell as it does say if cell.value in words and if I did row.value instead, it still doesn't work.

EDIT

I realise I need to iterate over rows so this is what I have so far, this turns it into a conditional format which is also fine if I can get it to work.

for rows in sheet.iter_rows(min_row=2, max_row=None, min_col=None, max_col=5):
    for cell in rows:
        words =  ['Total Assets', 'Total Liabilities & Equity']
        sheet.conditional_formatting.add(f'{cell.coordinate}',
                                             FormulaRule(formula=["=words(A{cell.row}))"],
                                                         border = tb_border))

The issue is in the selection of cells you want to update. As you are only selecting column A, that is the only one that is getting updated. In the original code you have provided, replace the last 5 lines with this...

words =  ['Assets', 'Current Assets', 'Liabilities']
for r_idx, row in enumerate(ws.iter_rows(max_row=ws.max_row, max_col=5)):
    if ws.cell(r_idx+1, 1).value in words:
        for cell in row:
            cell.font = header_style
            cell.border = tb_border

wb.save('yourfilename.xlsx')

...and you should get what you need... something like this.

在此处输入图像描述

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