pythonexcelopenpyxl

Want to change font color in excel using python


Not sure what wrong with code below, i want to give white color to the text

import openpyxl
from openpyxl import Workbook
from openpyxl.styles import Color, PatternFill, Font, Border
from openpyxl.styles import colors
from openpyxl.cell import Cell

wb = openpyxl.load_workbook('file.xlsx', read_only=False)
keep_sheets = ['sheet3','sheet2','sheet1']
for sheetName in wb.sheetnames:
    if sheetName in keep_sheets:
        ws = wb[sheetName]
        print(ws)
        fill_pattern = PatternFill(start_color='#4F81BD',
                   end_color='#4F81BD',
                   fill_type='solid')

        for col in range(1, colindex(sheetName)):  # 1 to 10 corresponds to A to J
            cell = ws.cell(row=1, column=col)
            cell.fill = fill_pattern
            cell.font = Font(color=colors.WHITE, bold=True)

# Save changes
wb.save('updated_file.xlsx')

on trying to apply I get error as below


ValueError: Colors must be aRGB hex values

Solution

  • There's a problem with you cell.font. So color.WHITE needs to be in RGB

    so updated code must be:

    cell.font = Font(color=colors.Color(colors.WHITE.get_hex_color()), bold=True)