使用Openpyxl突出显示单元格

2024-05-13 05:36:44 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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)

Tags: importtypecellcolumnredexcelfillcolor
1条回答
网友
1楼 · 发布于 2024-05-13 05:36:44

您的代码不保存工作簿。也许你没有发布全部代码, 但是如果您这样做了,那么您需要在末尾添加save()调用,以编写 对磁盘文件的更改

至于格式设置,这里有一个简单的例子,效果很好,它设置了 单元格D5(行=5,列=4)的背景色变为红色,单元格中的字体 C2(行=2,列=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')

相关问题 更多 >