Cell'对象没有'styles'属性,设置单元格字体颜色时出现问题

3 投票
2 回答
14115 浏览
提问于 2025-04-18 17:20

我正在使用 openpyxl 2.0.5 和 Python 3.4,想把一个单元格的字体颜色设置为红色。

from openpyxl import Workbook

from openpyxl.styles import Color, Font, Style, colors

wb = Workbook()

ws = wb.active

cell = 'A1'

ws[cell].styles = Style(font=Font(color=Color(colors.RED))) 

错误追踪(最近的调用最后): 文件 "C:/Users/b-rosard/PycharmProjects/Test/test.py",第 12 行, 在 ws[cell].styles = Style(font=Font(color=Color(colors.RED))) 处

AttributeError: 'Cell' 对象没有 'styles' 属性

我是在这里跟着示例操作的: http://openpyxl.readthedocs.org/en/latest/styles.html,但我不知道为什么会出现这个错误。

2 个回答

0

这段代码对我来说有效。我正在使用 Python 3.x。

from openpyxl.styles import Color, Font, PatternFill

book = Workbook()
output = book.active

cell = output.cell(row = some value, column = some value)

cell.fill = cell.fill.copy(patternType = 'solid', fgColor = 'FFFFFF00')

'FFFFFF00' 是用来表示黄色的

3

经过查看单元格的属性,发现了一个简单的解决办法。

ws[cell].style = Style(font=Font(color=Color(colors.RED))) 

撰写回答