简体   繁体   English

如何使用Apache POI在Excel文件中添加数据验证?

[英]How can I add Data Validation in excel files using Apache POI?

I'm using Apache POI to create an excel file that contains dropdown lists. 我正在使用Apache POI创建包含下拉列表的excel文件。 However, the dropdowns are still editable and the user will be able to type in values. 但是,下拉列表仍然可以编辑,用户可以输入值。 I've seen in excel that I can display an error message when a user enters a value that is not on the list. 我在excel中看到,当用户输入不在列表中的值时,我可以显示错误消息。 Below is the part of the code where I set the constraints. 下面是我设置约束的代码部分。

// Add dropdown for department column
    validationHelper = new XSSFDataValidationHelper(sheet);
    CellRangeAddressList addressList = new CellRangeAddressList(6, 10006, 2, 2);
// DVConstraint dvConstraint = DVConstraint.createExplicitListConstraint(departmentList);
    constraint = validationHelper.createExplicitListConstraint(departmentList);
    dataValidation = validationHelper.createValidation(constraint, addressList);
    dataValidation.setSuppressDropDownArrow(true);

    sheet.addValidationData(dataValidation);

I am able to display the list properly, however, it doesn't display an error message. 我能够正确显示列表,但是,它不会显示错误消息。 Is it possible to do this? 是否有可能做到这一点? If so, how can I do it? 如果是这样,我该怎么办? Any help is much appreciated. 任何帮助深表感谢。 Thanks. 谢谢。

You are missing the line 你错过了这条线

dataValidation.setShowErrorBox(true);

and you can customize the error box with 并且您可以使用自定义错误框

dataValidation.setErrorStyle(DataValidation.ErrorStyle.STOP);
dataValidation.createErrorBox("Title", "Message");

So together this is 所以这就是

var validationHelper = new XSSFDataValidationHelper(sheet);
var listConstraint = validationHelper.createExplicitListConstraint(departmentList);
var range = new CellRangeAddressList(6, 10006, 2, 2);

var dataValidation = validationHelper.createValidation(listConstraint, range);
dataValidation.setSuppressDropDownArrow(true);
dataValidation.setErrorStyle(DataValidation.ErrorStyle.STOP);
dataValidation.createErrorBox("Title", "Message");
dataValidation.setShowErrorBox(true);
sheet.addValidationData(dataValidation);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM