首页 > 解决方案 > 使用 Openpyxl 突出显示单元格

问题描述

我已经尝试了几个选项,如何在 python 3.8.2 中使用 Openpyxl 3.0.6 突出显示 excel 单元格,但下面的代码中没有一个对我有用,看起来可以运行,但没有突出显示单元格。

import openpyxl

from openpyxl.styles.fills import PatternFill
from openpyxl.styles import Font, colors

excel_path = openpyxl.load_workbook('C:/Users/Sample.xlsx')
currentSheet1 = excel_path['Template']
currentSheet3 = excel_path['Template Update']

#color the rows in sheet
redFill = PatternFill(patternType='solid', fgColor=colors.Color(rgb='00FF0000'))

currentSheet1.cell(row=20, column=11).fill= PatternFill(fill_type=None, start_color='F2DCDB', 
end_color='F2DCDB')

currentSheet1.cell(row=20, column=11).fill= PatternFill(fill_type=None, start_color='F2DCDB', 
end_color='F2DCDB')

ft = Font(color="FF0000")
a=currentSheet1.cell(row=20, column=10)
a.fill = PatternFill(fill_type = 'solid',bgColor='00ff00' )

fill_cell = currentSheet1.cell(row=20, column=10)
red_color = colors.Color(rgb='00FF0000')
solid_red_fill = PatternFill(patternType='solid', fgColor=red_color)
fill_cell.fill = solid_red_fill
currentSheet3.cell(row=1, column=1).fill = PatternFill(bgColor="FFC7CE", fill_type = "solid")
currentSheet1.cell(row=20, column=10).fill = PatternFill(fill_type="solid", bgColor=colors.BLUE)

标签: pythonopenpyxl

解决方案


您的代码不会保存工作簿。也许您没有发布整个代码,但如果您发布了,那么您需要在最后添加save()调用,将更改写入磁盘文件。

至于格式,这里有一个效果很好的简单示例,它将 单元格 D5 (row=5,col=4)的背景颜色设置为红色,将单元格 C2 (row=2, col=3) 中的字体设置为红色:

import openpyxl

from openpyxl.styles.fills import PatternFill
from openpyxl.styles import Font, colors

excel_path = openpyxl.load_workbook('C:/Users/Sample.xlsx')
currentSheet1 = excel_path['Template']
currentSheet3 = excel_path['Template Update']

#color the rows in sheet
redFill = PatternFill(patternType='solid', fgColor=colors.Color(rgb='00FF0000'))
currentSheet1.cell(row=5, column=4).fill = redFill

ft = Font(color="FF0000")
currentSheet1.cell(row=2, column=3).font = ft

excel_path.save(filename='C:/Users/Sample.xlsx')

推荐阅读