使用openpyxl库的DataValidation对象方法可添加下拉选择列表。
DataValidation参数说明:
- type: 数据类型("whole", "decimal", "list", "date", "time", "textLength", "custom")
- promptTitle :选定单元格后显示提示信息的标题
- prompt :选定单元格后显示提示信息的内容
- showDropDown 显示下拉箭头,默认False为显示
- allow_blank 允许空白,默认为False
- showInputMessage 输入内容后是否显示匹配的内容,默认为False
- showErrorMessage 不符合输入条件时报错提示信息显示,默认为False
DataValidation可接收两个公式参数formula1 和formula12 ,根据不同的type添加一个或两个公式参数,如果type类型只接收一个公式时,则取formula1为公式。
接收两个公式参数时,可选择operator参数,参数可选值有:"between", "notBetween", "equal", "notEqual", "lessThan", "lessThanOrEqual", "greaterThan", "greaterThanOrEqual"。
参数与Excel关系:







代码演示:
python
from openpyxl import Workbook
from openpyxl.worksheet.datavalidation import DataValidation
# 创建一个新的工作簿
wb = Workbook()
ws = wb.create_sheet('666', index=0)
# 设置下拉列表的选项
options = ["张三", "李四", "王五"]
# 创建数据验证对象
dv = DataValidation(type="list", formula1='"{}"'.format(','.join(options)),
prompt='选择与选项匹配的内容',
promptTitle='请选择姓名',
allow_blank=True,
showErrorMessage=True,
showInputMessage=True, showDropDown=False)
# showInputMessage 输入时模糊首先展示匹配的数据供选择
# showErrorMessage 输入后校验输入的数据是够在选择项当中,不在时给出错误提示,错误提示信息如下:
dv.errorTitle = "无效的选择"
dv.errorStyle = 'warning' # 错误警告的样式,默认为stop,("stop", "warning", "information")
dv.error = "请选择或输入与下拉数据匹配的数据!"
ws.add_data_validation(dv) # 将数据验证规则添加到工作表中
# 将数据验证应用于A2:A100单元格区域
dv.add("A2:A100")
# 将数据验证添加到工作表
ws.add_data_validation(dv)
# 保存Excel文件
wb.save(rf'C:\Users\Administrator\Desktop\test001.xlsx')
补充小知识:可手动在条件筛选中设置每个下拉选择的样式
