简体   繁体   English

使用 openpyxl 用 colors 填充单元格?

[英]Fill cells with colors using openpyxl?

I am currently using openpyxl v2.2.2 for Python 2.7 and i wanted to set colors to cells.我目前正在为 Python 2.7 使用 openpyxl v2.2.2,我想将 colors 设置为单元格。 I have used the following imports我使用了以下进口

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(或任何其他单元格)设置为 colors 的任何想法?

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应该可以正常工作。

The API for styles changed once again.样式的 API 再次更改。 What worked for me was对我有用的是

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.颜色是 alpha RGB 十六进制颜色。 You can pass it in as 'rrggbb' with a default alpha of 00 or specify the alpha with 'aarrggbb' .您可以将其作为'rrggbb' ,默认 alpha 为 00 或使用'aarrggbb'指定 alpha。 A bunch of colors are defined as constants in openpyxl.styles.colors if you need to grab one quickly.如果您需要快速获取一个,在openpyxl.styles.colors一堆颜色定义为常量。

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

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.xi hope working just put ws['A1'].fill=redFill那工作,但我不知道在 python 2.xi 希望工作只是把ws['A1'].fill=redFill

What I would do for Excel is this:我会为 Excel 做的是:

from openpyxl import Workbook, load_workbook
from openpyxl.styles import PatternFill

wb = load_workbook("test.xlsx")
ws = wb.active

ws["A1"].fill = PatternFill("solid", start_color="FFA500")

You can replace "A1" with another cell and start_color has to be a hex color.您可以用另一个单元格替换“A1”,并且 start_color 必须是十六进制颜色。

from openpyxl import Workbook, load_workbook
from openpyxl.styles import PatternFill

_file_name = "Test.xlsx"
_sheet_name = "Test_Sheet"

def new_workbook(_file_name, _sheet_name):
    wb = Workbook()  # Workbook Object
    ws = wb.active  # Gets the active worksheet
    ws.title = _sheet_name  # Name the active worksheet

    # Writing the header columns
    ws['A1'] = 'Name'
    ws['B1'] = 'Class'
    ws['C1'] = 'Section'
    ws['D1'] = 'Marks'
    ws['E1'] = 'Age'
    

    col_range = ws.max_column  # get max columns in the worksheet

    # formatting the header columns, filling red color
    for col in range(1, col_range + 1):
        cell_header = ws.cell(1, col)
        cell_header.fill = PatternFill(start_color='FF0000', end_color='FF0000', fill_type="solid") #used hex code for red color

    wb.save(_file_name)  # save the workbook
    wb.close()  # close the workbook

if __name__ == '__main__':
new_workbook(_file_name, _sheet_name)

Result -结果 - 在此处输入图片说明

To fill a range of rows/columns, do this要填充一系列行/列,请执行以下操作

for cell in ws['A1:A100']:
   cell[0].fill = redFill

To fill all rows of a column填充一列的所有行

for cell in ws['A1:{}'.format(ws.max_row)]:
   cell[0].fill = redFill

Use a nested for loop to fill a two dimensional range.使用嵌套的 for 循环来填充二维范围。

Python 3.9蟒蛇 3.9

import openpyxl as op
fill_gen = op.styles.PatternFill(fill_type='solid',
                                 start_color='FFFFFF',
                                 end_color='FFFFFF')
for row in ws["A1:BB50"]:
    for cell in row:
        cell.fill = fill_gen

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM