在 Python 的 openpyxl 中用颜色填充行 Excel

Fill rows Excel with color in openpyxl of Python

如果事先不知道要填充的行号,如何在openpyxl中用颜色填充行? headers 行位于未知数据行部分的开头,例如:

from openpyxl import load_workbook, Workbook
from openpyxl.styles import PatternFill
import random
wb = Workbook()
ws = wb.active

for section in range(10):
    header_row = ('col1', 'col2')
    ws.append(header_row)   # Wanted to fill this
    random_amount_rows = [('bar', 'foo') for i in range(1, random.randrange(2,10))]
    for datarow in random_amount_rows: 
        ws.append(datarow)

一般情况下,知道行号的情况下,可以填写如下:

fill = PatternFill("solid", fgColor="DDDDDD")
for cell in list(ws.rows)[rownumber]:
    cell.fill = fill

您可以附加单元格而不是值,从而应用格式。请参阅文档中有关只写模式的部分。 http://openpyxl.readthedocs.io/en/latest/optimized.html#write-only-mode

通过只写模式工作如下。谢谢,查理·克拉克。

from openpyxl.worksheet.write_only import WriteOnlyCell
fill = PatternFill("solid", fgColor="DDDDDD")   

for section in sections:
    row_to_fill_texts = ('col1', 'col2')
    row = []
    for h in row_to_fill_texts:
        cell = WriteOnlyCell(ws, value=h)
        cell.fill = fill
        row.append(cell)
    ws.append(row)
    # adding other lines