Starting with 3.8, the POI uses. xls and. xlsx format to handle data validation in a slightly different place.
1) Check the value of the user input to the cell for one or more pre-defined values
The following code restricts the value that the user can enter into cell A1 to be one of three integer values (10, 20, 30):
Workbook Workbook = new Xssfworkbook (); or new Hssfworkbook.
Sheet Sheet = Workbook.createsheet ("Data Validation");
Data Validation Helper Classes
Datavalidationhelper dvhelper = Sheet.getdatavalidationhelper ();
Create an expected list constraint, an array parameter that requires expected values
Datavalidationconstraint dvconstraint = dvhelper.createexplicitlistconstraint (new string[]{"13", "23", "33"});
Cell array reference, which is cell A1 (first row index, last row index, first column index, last column index)
Cellrangeaddresslist AddressList = new Cellrangeaddresslist (0, 0, 0, 0);
Create data validation using data validation constraints and cell references
datavalidation validation = dvhelper.createvalidation (Dvconstraint, AddressList);
The settings for the 2003 and 2007 formats are slightly different here
if (validation instanceof xssfdatavalidation) {
Validation.setsuppressdropdownarrow (FALSE);
Validation.setshowerrorbox (TRUE);
} else {
Validation.setsuppressdropdownarrow (TRUE);
}
Sheet.addvalidationdata (validation);
2) Download list
The code will do the same thing, but provide the user to select a value from the drop-down list.
Workbook Workbook = new Xssfworkbook (); or new Hssfworkbook
Sheet Sheet = Workbook.createsheet ("Data Validation");
Datavalidationhelper dvhelper = Sheet.getdatavalidationhelper ();
Datavalidationconstraint dvconstraint = dvhelper.createexplicitlistconstraint (new string[]{"13", "23", "33"});
Cellrangeaddresslist AddressList = new Cellrangeaddresslist (0, 0, 0, 0);
datavalidation validation = dvhelper.createvalidation (Dvconstraint, AddressList);
if (validation instanceof xssfdatavalidation) {
Validation.setsuppressdropdownarrow (TRUE);
Validation.setshowerrorbox (TRUE);
} else {
Validation.setsuppressdropdownarrow (FALSE);
}
Sheet.addvalidationdata (validation);
3) Custom Error messages
The Create message box shows that the value entered by the user is not valid.
Set error style, valid value stop, WARNING, INFO
Validation.seterrorstyle (DataValidation.ErrorStyle.STOP);
Set the title and message of the error prompt box
Validation.createerrorbox ("Box Title", "Message Text");
4) Tips
The user will see a prompt when the cell containing the data validation gets the focus.
Validation.createpromptbox ("Title", "Message Text");
Validation.setshowpromptbox (TRUE);
5) More advanced data validation
Similar to the Dvhelper.createexplicitlistconstraint Datavalidationhelper class, a series of createxxxconstraint methods are defined to implement various Excel validation functions.
POI Data validation