为什么我的代码没有使用 Python 中的 openpyxl 更改 excel 中单元格的背景颜色?

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

我需要用python更改excel中某些单元格的颜色。

我尝试过使用 openpyxl 但它无法正常工作。

首先,我拿起文件并打开正确的工作表

import os, openpyxl
from openpyxl.styles import PatternFill

file = os.getcwd() + '\\File.xlsx'
wb = load_workbook(file)
sheet = wb.active

然后,我尝试选择单元格并更改颜色

# Specify the range of cells

cell = sheet['A1']


# Create the fill color

cell.fill = PatternFill(start_color='FF0000', end_color='FF0000', fill_type='solid')  # Red color

wb.save(file)

当我运行此代码时,我没有收到任何错误,但它没有进行任何更改

python openpyxl
2个回答
0
投票

这将完成工作

from openpyxl.styles import PatternFill, Color


cell.fill = PatternFill(patternType='solid', fill_type='solid', fgColor=Color('FF0000'))

0
投票

我不知道这是否是你的问题,但这对我来说很有效

from openpyxl.styles import PatternFill, Color

cell.fill = PatternFill(patternType='solid', fill_type='solid', fgColor=Color('FF0000'))

wb.save(file)

它与其他答案之一的代码相同,但随后保存了更改,我忘记了在我的一个项目中,这是我问题的答案,希望它有帮助

© www.soinside.com 2019 - 2024. All rights reserved.