如果填充的行号提前未知,如何在openpyxl中填充颜色的行?它是一系列标题,位于未知数量的数据行的开头,例如:
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
答案 0 :(得分:3)
您可以追加单元格而不是值,从而应用格式。请参阅文档中有关只写模式的部分。 http://openpyxl.readthedocs.io/en/latest/optimized.html#write-only-mode
答案 1 :(得分:1)
通过只写模式工作如下。谢谢,查理克拉克。
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