想要使用python更改excel中的字体颜色(待打开)[已关闭]

问题描述 投票:0回答:2

不确定下面的代码有什么问题,我想给文本赋予白色

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')

尝试申请时出现如下错误


ValueError: Colors must be aRGB hex values
python excel openpyxl
2个回答
-1
投票

你有问题

cell.font
。所以
color.WHITE
需要是 RGB

所以更新的代码必须是:

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


-1
投票

下面的代码对我有用:

fill_pattern = PatternFill(start_color='4F81BD',
                   end_color='4F81BD',
                   fill_type='solid')

for col in range(3, colindex(sheetName)): 
            cell = ws.cell(row=5, column=col)
            cell.fill = fill_pattern
            cell.font = Font(color='FFFFFF', bold=True)
            cell.value = cell.value.replace("_"," ") 
            cell.value = cell.value.title()
            print("done")
© www.soinside.com 2019 - 2024. All rights reserved.