python - 使用 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)
解决方案
您的代码不会保存工作簿。也许您没有发布整个代码,但如果您发布了,那么您需要在最后添加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')
推荐阅读
- java - 从 HDFS 读取 protobuf 文件时出现 NoSuchMethodError 异常
- c++ - 离开作用域后如何保护局部变量的值?
- elixir - 从 Elixir 的列表中删除最后一个元素?
- json - SQL Server 文档存储与 MongoDB
- mysql - 尝试连接到 PostgreSQL 数据库时出错
- botframework - Botframework - 地图不是函数
- javascript - 隐藏和取消隐藏列会更改列的自动宽度
- c# - 是什么导致 MSSQL 中出现“非阻塞套接字上的操作会阻塞”错误?
- c++ - 将最多 50 位的 2 个数字相乘
- c++ - C++中的新运算符重载