简体   繁体   中英

How to fill background color of excel base on cell value with Python?

  1. I have a list of excel.

在此处输入图像描述

  1. I use python to found duplicate record and update to excel.

     import openpyxl as xl import pandas as pd df = pd.read_excel('C:/Users/User/Desktop/List.xlsx') df['Duplicate'] = df.duplicated(['Country', 'Name'], keep=False) upd_col_d = df['Duplicate'] wb = xl.load_workbook('C:\\Users\\User\\Desktop\\List.xlsx') ws = wb.active for df_row, df_value in enumerate(upd_col_d, start=2): ws[f'D{df_row}'].value = df_value wb.save('C:\\Users\\User\\Desktop\\List.xlsx')
  2. The updated list

在此处输入图像描述

  1. I want to use below function fill the row is yellow if column D value is TRUE but not work... Could tell me what is wrong with my function?

     import openpyxl as xl from openpyxl import Workbook from openpyxl.styles import Color, PatternFill, Font, Border from openpyxl.formatting.rule import Rule from openpyxl.styles.differential import DifferentialStyle def background_colors(path): wb = xl.load_workbook('C:\\Users\\User\\Desktop\\List.xlsx') ws = wb.active yellow = "00FFFF00" for rows in sheet.iter_rows(min_row=1, max_row=1, min_col=1, max_col=3): for cell in rows: if cell == 'TRUE': cell.fill = PatternFill(start_color=yellow, end_color=yellow, fill_type="solid") workbook.save(path) if __name__ == "__main__": background_colors('C:\\Users\\User\\Desktop\\List.xlsx')

Few edits, but given the excel as was in the picture above, this code will read, update and save back the file with the rows marked as TRUE with yellow color.

import openpyxl as xl
from openpyxl import Workbook
from openpyxl.styles import Color, PatternFill, #Font, Border
#from openpyxl.formatting.rule import Rule
#from openpyxl.styles.differential import DifferentialStyle 

def background_colors(path):
    wb = xl.load_workbook(path)
    ws = wb.active
    yellow = "FFFF00"   #Correct HEX code for yellow
    for row in ws.iter_rows(min_row=2, max_row=ws.max_row, min_col=1, max_col=4):
        if str(ws.cell(row[0].row, 4).value).upper() == 'TRUE': #As true is reserved word, had to convert to string and then upper case
            for cell in row:
                cell.fill = PatternFill("solid", fgColor=yellow)
    wb.save(path)

if __name__ == "__main__":
    background_colors('C:\\Users\\User\\Desktop\\List.xlsx')

Output sheet

在此处输入图像描述

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