验证 Cell 值是否满足数据验证规则
验证 Cell 值是否满足数据验证规则
有时,需要动态验证给定值是否满足应用于单元格的数据验证规则。为此,Aspose.Cells API 提供了[cell.getValidationValue](https://reference.aspose.com/cells/java/com.aspose.cells/cell#getValidationValue() ) 方法。如果单元格中的值不满足应用于该单元格的数据有效性规则,则返回错误的, 别的真的.
以下示例 Microsoft Excel 文件与下面的示例代码一起用于测试[cell.getValidationValue](https://reference.aspose.com/cells/java/com.aspose.cells/cell#getValidationValue()) 方法。正如您在快照中看到的那样,细胞C1已十进制数据验证应用并且只接受值10 到 20 之间.每当单元格的值介于 10 和 20 之间时,cell.getValidationValue 方法将返回真的 否则返回错误的.
下面的示例代码说明了如何[cell.getValidationValue](https://reference.aspose.com/cells/java/com.aspose.cells/cell#getValidationValue() 方法有效。首先,它将值 3 输入 C1。因为这不满足数据验证规则,所以[cell.getValidationValue](https://reference.aspose.com/cells/java/com.aspose.cells/cell#getValidationValue() 方法返回错误的.然后,它将值 15 输入 C1。因为这个值满足数据验证规则,所以[cell.getValidationValue](https://reference.aspose.com/cells/java/com.aspose.cells/cell#getValidationValue() 方法返回真的.同样,它返回错误的价值 30。
Java 验证 Cell 值是否满足数据验证规则的代码
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java | |
// The path to the documents directory. | |
String dataDir = Utils.getDataDir(VerifyCellValueSatisfiesDataValidationRules.class); | |
// Instantiate the workbook from sample Excel file | |
Workbook workbook = new Workbook(dataDir + "Sample1.xlsx"); | |
// Access the first worksheet | |
Worksheet worksheet = workbook.getWorksheets().get(0); | |
/* | |
* Access Cell C1. Cell C1 has the Decimal Validation applied on it.It can take only the values Between 10 and 20 | |
*/ | |
Cell cell = worksheet.getCells().get("C1"); | |
// Enter 3 inside this cell. Since it is not between 10 and 20, it should fail the validation | |
cell.putValue(3); | |
// Check if number 3 satisfies the Data Validation rule applied on this cell | |
System.out.println("Is 3 a Valid Value for this Cell: " + cell.getValidationValue()); | |
// Enter 15 inside this cell. Since it is between 10 and 20, it should succeed the validation | |
cell.putValue(15); | |
// Check if number 15 satisfies the Data Validation rule applied on this cell | |
System.out.println("Is 15 a Valid Value for this Cell: " + cell.getValidationValue()); | |
// Enter 30 inside this cell. Since it is not between 10 and 20, it should fail the validation again | |
cell.putValue(30); | |
// Check if number 30 satisfies the Data Validation rule applied on this cell | |
System.out.println("Is 30 a Valid Value for this Cell: " + cell.getValidationValue()); | |
示例代码生成的控制台输出
这是使用上面显示的示例 Excel 文件执行示例代码时生成的控制台输出。
Is 3 a Valid Value for this Cell: False
Is 15 a Valid Value for this Cell: True
Is 30 a Valid Value for this Cell: False