系统:Windows 7
语言版本:Anaconda3-4.3.0.1-Windows-x86_64
编辑器:pycharm-community-2016.3.2
openpyxl:2.6.2
- 这个系列讲讲Python对Excel的操作
- 使用openpyxl模块
- 今天讲讲单元格背景色设置
Part 1:代码
from openpyxl import load_workbook
from openpyxl.styles import PatternFill, colors
excel_address = r"E:\Coding\E_PythonWriting\Excel\openpyxl示例_4.xlsx"
wb = load_workbook(excel_address)
sht = wb.worksheets[0]
sht["A1"] = "测试"
sht["A3"] = "测试"
sht["A5"] = "测试"
sht["A7"] = "测试"
fill_1 = PatternFill("solid", fgColor="1874CD")
fill_2 = PatternFill("solid", fgColor="BCEE68")
fill_3 = PatternFill("solid", fgColor=colors.RED)
fill_4 = PatternFill("solid", fgColor=colors.GREEN)
sht["A1"].fill = fill_1
sht["A3"].fill = fill_2
sht["A5"].fill = fill_3
sht["A7"].fill = fill_4
wb.save(excel_address)
代码截图
执行结果
Part 2:部分代码解读
- 和上一篇中的字体和对齐一样,关于背景色有一个类
PatternFill
,单元格有fill属性 - 关于颜色,可以使用colors.RED,也可以使用16进制颜色码,每一种颜色对应的编码可以网上查一下
- 底色方式有多种,文中使用了两种:"solid","lightVertical"。一般使用solid即可
颜色的取值
底色方式
本文为原创作品,欢迎分享朋友圈
常按图片识别二维码,关注本公众号
Python 优雅 帅气