openpyxl 设置单元格背景颜色

问题描述 投票:0回答:1

我想用彩色背景填充这些框,因为它们是附加在Excel文件上的元素,我无法定义框的编号...

有什么想法吗?

ws.append([datumcleaned,tagsinfo,])

这是他的代码:

# Writing on a EXCEL FILE
filename = f"{myPath}/Monatsplan {userfinder} {month} {year}.xlsx"
try:
    wb = load_workbook(filename)
    ws = wb.worksheets[0]  # select first worksheet
except FileNotFoundError:
    headers_row = ['Datum', 'Dienst','Funktion','Von','Bis','Schichtdauer','Bezahlte Zeit']
    wb = Workbook()
    ws = wb.active
    ws.append(headers_row)
wb.save(filename)
ws.append([datumcleaned,tagesinfo,])
wb.save(filename)
wb.close()
python colors background openpyxl
1个回答
0
投票

您最好的选择是使用

.iter_cols()
迭代现有列,并将背景颜色应用于每列的索引号 -1,因为附加行是最后一个索引:

for cols in ws.iter_cols():
if cols[-1].value: # need to check the cells have values.
                  # otherwise colors the entire row.
    cols[-1].fill = PatternFill(bgColor="FFC7CE", fill_type="solid")
© www.soinside.com 2019 - 2024. All rights reserved.