Openpyxl: Excel file created is not showing validation errors or prompt message

Question:

I am generating a excel file using openpyxl and adding a list as a validation. I am successfully able to create the drop down list but when I add invalid data in the validated column it shows no error or prompt even though I have specified it in the code here is my code taken directly from the official documentation:

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")

However when I see the data validation option in the excel file I see that for the given column data validation using list is present but the show "input message when cell is selected" and "show error message on invalid data" checkbox in unchecked, once I manually check these the data validation starts working as expected, Is there any way to do this programtically??

Asked By: Ryan

||

Answers:

As @Charlie Clark pointed you have to explicitly set them as true.
You need to add the following to your code

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)

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

wb.save("demo.xlsx")
Answered By: Himanshu
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.