Openpyxl:创建的 Excel 文件未显示验证错误或提示消息

问题描述 投票:0回答:0

我正在使用 openpyxl 生成一个 excel 文件并添加一个列表作为验证。我能够成功地创建下拉列表,但是当我在验证列中添加无效数据时,即使我在代码中指定了它,它也没有显示任何错误或提示,这里是我的代码直接取自官方文档:

from openpyxl import Workbook
from openpyxl.worksheet.datavalidation import DataValidation

# Create the workbook and worksheet we'll be working with
wb = Workbook()
ws = wb.active

#Create a data-validation object with list validation
dv = DataValidation(type="list", formula1='"Dog,Cat,Bat"', allow_blank=True)
# Optionally set a custom error message
dv.error ='Your entry is not in the list'
dv.errorTitle = 'Invalid Entry'

# Optionally set a custom prompt message
dv.prompt = 'Please select from the list'
dv.promptTitle = 'List Selection'

# Add the data-validation object to the worksheet
ws.add_data_validation(dv)
# Create some cells, and add them to the data-validation object
c1 = ws["A1"]
c1.value = "Dog"
dv.add(c1)
c2 = ws["A2"]
c2.value = "An invalid value"
dv.add(c2)

# Or, apply the validation to a range of cells
dv.add('B1:B1048576') # adding validation for the whole column

wb.save("demo.xlsx")

但是,当我在 excel 文件中看到数据验证选项时,我看到对于给定的列,使用列表的数据验证存在,但未选中显示“选择单元格时输入消息”和“显示无效数据错误消息”复选框,一旦我手动检查这些数据验证开始按预期工作,有没有办法以编程方式执行此操作??

python excel openpyxl
© www.soinside.com 2019 - 2024. All rights reserved.