Python 使用 openpyxl 用颜色填充单元格?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30484220/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Fill cells with colors using openpyxl?
提问by Ahmed Rashad
I am currently using openpyxl v2.2.2 for Python 2.7 and i wanted to set colors to cells. I have used the following imports
我目前正在为 Python 2.7 使用 openpyxl v2.2.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
and the following is the code I tried using:
以下是我尝试使用的代码:
wb = openpyxl.Workbook()
ws = wb.active
redFill = PatternFill(start_color='FFFF0000',
end_color='FFFF0000',
fill_type='solid')
ws['A1'].style = redFill
but I get the following error:
但我收到以下错误:
Traceback (most recent call last)
self.font = value.font.copy()
AttributeError: 'PatternFill' object has no attribute 'font'
Any idea on how to set cell A1 (or any other cells) with colors using openpyxl?
关于如何使用 openpyxl 设置带有颜色的单元格 A1(或任何其他单元格)的任何想法?
采纳答案by Charlie Clark
I believe the issue is that you're trying to assign a fill object to a style.
我相信问题在于您试图将填充对象分配给样式。
ws['A1'].fill = redFill
should work fine.
ws['A1'].fill = redFill
应该工作正常。
回答by M T Head
This worked for me. They changed things and most of the help you see on the internet is for older versions of the openpyxl library from what I am seeing.
这对我有用。他们改变了一些东西,你在互联网上看到的大部分帮助都是针对我所看到的旧版本的 openpyxl 库。
# Change background color
xls_cell.style = Style(fill=PatternFill(patternType='solid',
fill_type='solid',
fgColor=Color('C4C4C4')))
回答by ldrg
The API for styles changed once again. What worked for me was
样式的 API 再次更改。对我有用的是
my_red = openpyxl.styles.colors.Color(rgb='00FF0000')
my_fill = openpyxl.styles.fills.PatternFill(patternType='solid', fgColor=my_red)
cell.fill = my_fill
Color is an alpha RGB hex color. You can pass it in as 'rrggbb'
with a default alpha of 00 or specify the alpha with 'aarrggbb'
. A bunch of colors are defined as constants in openpyxl.styles.colors
if you need to grab one quickly.
颜色是 alpha RGB 十六进制颜色。您可以将其作为'rrggbb'
默认 alpha 值 00传入或使用'aarrggbb'
. openpyxl.styles.colors
如果您需要快速获取一个颜色,则将一堆颜色定义为常量。
回答by ismail
in python 3.x
在 python 3.x 中
wb = openpyxl.Workbook()
ws = wb.active
redFill = PatternFill(start_color='FFFF0000',
end_color='FFFF0000',
fill_type='solid')
ws['A1'].fill = redFill
that working but i dont know in python 2.x i hope working
just put ws['A1'].fill=redFill
那个工作,但我不知道在 python 2.xi 希望工作只是把 ws['A1'].fill=redFill