简体   繁体   English

如何使用Python根据单元格值填充excel的背景颜色?

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

  1. I have a list of excel.我有一个excel列表。

在此处输入图像描述

  1. I use python to found duplicate record and update to excel.我使用python查找重复记录并更新为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?如果 D 列的值为 TRUE 但不起作用,我想使用下面的函数填充该行是黄色的......可以告诉我我的函数有什么问题吗?

     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.几乎没有编辑,但鉴于上图中的 excel,此代码将读取、更新并保存文件,其中行标记为TRUE并用黄色标记。

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输出表

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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