Adding Data Validation in Excel Using Python Code

Share office file processing skills in .NET, Java, and C++.
When working with spreadsheet data, ensuring the accuracy and consistency of input is crucial. The data validation feature allows developers to set rules that restrict what users can enter into cells, thereby preventing invalid data entry. This article demonstrates how to add various types of data validation rules to Excel worksheets using Python.
Why Data Validation Is Needed Data validation serves multiple purposes in practical applications:
Ensure Data Quality: Restrict input ranges to avoid invalid data Improve User Experience: Provide clear error messages and guidance Simplify Data Processing: Reduce the workload for subsequent data cleaning Automate Form Control: Create standardized data entry templates Common validation scenarios include numeric range restrictions, date validity checks, text length controls, and more.
Environment Setup First, install the Spire.XLS for Python library:
pip install Spire.XLS This library provides a complete API for Excel file operations, supporting the creation, modification, and formatting of Excel documents.
Basic Implementation Steps The core process for adding data validation includes:
Load or create an Excel workbook Get the target worksheet Specify the cell range where validation should be applied Configure validation rules (type, conditions, error messages) Save the file The following examples demonstrate how to implement different types of data validation.
Adding Numeric Range Validation Numeric validation is the most common validation type, restricting users to enter only numbers within a specific range. The following code demonstrates how to set up a decimal number validation between 3 and 6:
from spire.xls import * from spire.xls.common import *
Create workbook object
workbook = Workbook() sheet = workbook.Worksheets[0]
Add description label
sheet.Range["B11"].Text = "Enter a number (3-6):"
Get target cell range
rangeNumber = sheet.Range["B12"]
Set comparison operator to "Between"
rangeNumber.DataValidation.CompareOperator = ValidationComparisonOperator.Between
Set minimum and maximum values
rangeNumber.DataValidation.Formula1 = "3" rangeNumber.DataValidation.Formula2 = "6"
Specify validation type as decimal
rangeNumber.DataValidation.AllowType = CellDataType.Decimal
Set error message
rangeNumber.DataValidation.ErrorMessage = "Please enter a valid number."
Enable error display
rangeNumber.DataValidation.ShowError = True
Set cell background color to identify validation area
rangeNumber.Style.KnownColor = ExcelColors.Gray25Percent
Auto-fit column width
sheet.AutoFitColumn(2)
Save file
workbook.SaveToFile("NumericValidation.xlsx", ExcelVersion.Version2010) workbook.Dispose() Key API explanations:
CompareOperator: Defines the comparison method, such as Between, Greater, Less, etc. Formula1 and Formula2: Set boundary values for validation conditions AllowType: Specifies the data type, such as Decimal, Integer, etc. ErrorMessage: Error message displayed when input is invalid ShowError: Controls whether to display the error dialog box Adding Date Validation Date validation ensures that users enter dates within a valid range. This is particularly useful when handling schedules, deadlines, and similar scenarios:
from spire.xls import * from spire.xls.common import *
workbook = Workbook() sheet = workbook.Worksheets[0]
Add description label
sheet.Range["B14"].Text = "Enter a date"
Get target cell
rangeDate = sheet.Range["B15"]
Set validation type to date
rangeDate.DataValidation.AllowType = CellDataType.Date
Set comparison operator
rangeDate.DataValidation.CompareOperator = ValidationComparisonOperator.Between
Set date range (January 1, 1970 to December 31, 1970)
rangeDate.DataValidation.Formula1 = "1/1/1970" rangeDate.DataValidation.Formula2 = "12/31/1970"
Set error message
rangeDate.DataValidation.ErrorMessage = "Please enter a valid date."
Enable error display
rangeDate.DataValidation.ShowError = True
Set warning style (optional: Stop, Warning, Information)
rangeDate.DataValidation.AlertStyle = AlertStyleType.Warning
Set cell background color
rangeDate.Style.KnownColor = ExcelColors.Gray25Percent
sheet.AutoFitColumn(2)
workbook.SaveToFile("DateValidation.xlsx", ExcelVersion.Version2010) workbook.Dispose() Date formats can use various standard representations, such as "MM/DD/YYYY" or "YYYY-MM-DD". The AlertStyleType provides three error prompt styles:
Stop: Prevents users from entering invalid data Warning: Warns but allows continuation Information: Provides informational prompts only Adding Text Length Validation Text length validation controls the maximum or minimum number of characters in a string, suitable for fields like usernames, passwords, codes, etc.:
from spire.xls import * from spire.xls.common import *
workbook = Workbook() sheet = workbook.Worksheets[0]
Add description label
sheet.Range["B17"].Text = "Enter text"
Get target cell
rangeTextLength = sheet.Range["B18"]
Set validation type to text length
rangeTextLength.DataValidation.AllowType = CellDataType.TextLength
Set comparison operator to "LessOrEqual"
rangeTextLength.DataValidation.CompareOperator = ValidationComparisonOperator.LessOrEqual
Set maximum length to 5 characters
rangeTextLength.DataValidation.Formula1 = "5"
Set error message
rangeTextLength.DataValidation.ErrorMessage = "Please enter a valid string."
Enable error display
rangeTextLength.DataValidation.ShowError = True
Set stop style to strictly prevent invalid input
rangeTextLength.DataValidation.AlertStyle = AlertStyleType.Stop
Set cell background color
rangeTextLength.Style.KnownColor = ExcelColors.Gray25Percent
sheet.AutoFitColumn(2)
workbook.SaveToFile("TextLengthValidation.xlsx", ExcelVersion.Version2010) workbook.Dispose() Text length validation supports various comparison operators:
LessOrEqual: Less than or equal to the specified length GreaterOrEqual: Greater than or equal to the specified length Between: Between two length values Equal: Equal to the specified length Comprehensive Example: Adding Multiple Validations in One File In practical applications, it's common to apply multiple validation rules within the same worksheet. Here's a complete example integrating the three validation types mentioned above into one file:
from spire.xls import * from spire.xls.common import *
Create workbook
workbook = Workbook() sheet = workbook.Worksheets[0]
=== Numeric Validation ===
sheet.Range["B11"].Text = "Enter a number (3-6):" rangeNumber = sheet.Range["B12"] rangeNumber.DataValidation.CompareOperator = ValidationComparisonOperator.Between rangeNumber.DataValidation.Formula1 = "3" rangeNumber.DataValidation.Formula2 = "6" rangeNumber.DataValidation.AllowType = CellDataType.Decimal rangeNumber.DataValidation.ErrorMessage = "Please enter a valid number." rangeNumber.DataValidation.ShowError = True rangeNumber.Style.KnownColor = ExcelColors.Gray25Percent
=== Date Validation ===
sheet.Range["B14"].Text = "Enter a date" rangeDate = sheet.Range["B15"] rangeDate.DataValidation.AllowType = CellDataType.Date rangeDate.DataValidation.CompareOperator = ValidationComparisonOperator.Between rangeDate.DataValidation.Formula1 = "1/1/1970" rangeDate.DataValidation.Formula2 = "12/31/1970" rangeDate.DataValidation.ErrorMessage = "Please enter a valid date." rangeDate.DataValidation.ShowError = True rangeDate.DataValidation.AlertStyle = AlertStyleType.Warning rangeDate.Style.KnownColor = ExcelColors.Gray25Percent
=== Text Length Validation ===
sheet.Range["B17"].Text = "Enter text" rangeTextLength = sheet.Range["B18"] rangeTextLength.DataValidation.AllowType = CellDataType.TextLength rangeTextLength.DataValidation.CompareOperator = ValidationComparisonOperator.LessOrEqual rangeTextLength.DataValidation.Formula1 = "5" rangeTextLength.DataValidation.ErrorMessage = "Please enter a valid string." rangeTextLength.DataValidation.ShowError = True rangeTextLength.DataValidation.AlertStyle = AlertStyleType.Stop rangeTextLength.Style.KnownColor = ExcelColors.Gray25Percent
Auto-fit column width
sheet.AutoFitColumn(2)
Save file
workbook.SaveToFile("DataValidation.xlsx", ExcelVersion.Version2010) workbook.Dispose() Practical Tips Custom Dropdown List Validation In addition to the validation types mentioned above, dropdown lists can also be created for user selection:
Create dropdown list validation
rangeList = sheet.Range["C5"] rangeList.DataValidation.AllowType = CellDataType.List rangeList.DataValidation.Formula1 = '"Option 1,Option 2,Option 3"' rangeList.DataValidation.ShowDropDown = True Note: Dropdown list options need to be enclosed in double quotes and separated by commas.
Referencing Validation Data from Cell Ranges Validation data can be dynamically read from other cell ranges:
Read list data from range A1:A5
rangeDynamic = sheet.Range["D5"] rangeDynamic.DataValidation.AllowType = CellDataType.List rangeDynamic.DataValidation.Formula1 = "=A1:A5" This approach allows dynamic updates to validation options without modifying the code.
Clearing Data Validation To remove existing validation rules:
Clear validation for specified cells
rangeToClear.DataValidation.Clear() Summary This article demonstrated how to add data validation in Excel using Python, including numeric range validation, date validation, and text length validation. By properly configuring the properties of the DataValidation object, flexible data input control can be achieved, improving spreadsheet data quality and user experience.
These techniques are particularly applicable to:
Creating standardized data entry templates Building data collection forms Implementing data quality control processes Developing automated reporting systems After mastering data validation techniques, they can be combined with other Excel operations (such as conditional formatting, formula calculations, etc.) to build more comprehensive automated office solutions.

