验证单元格值是否满足数据验证规则

验证单元格值是否符合数据验证规则

有时,动态验证给定值是否满足应用于单元格的数据验证规则是必要的。为此,Aspose.Cells API提供了cell.getValidationValue()方法。如果单元格中的值不满足应用于该单元格的数据验证规则,则返回False,否则返回True

使用以下示例 Microsoft Excel 文件与下面的示例代码一起测试 cell.getValidationValue() 方法。从快照中可以看到,单元格 C1 应用了 十进制数据验证,并且只接受 10 到 20 之间的值。每当单元格的值在 10 到 20 之间,cell.getValidationValue() 方法会返回 True,否则返回 False

todo:image_alt_text

以下示例代码说明了 cell.getValidationValue() 方法的工作原理。首先,它将值 3 输入到 C1 中。因为这不符合数据验证规则,cell.getValidationValue() 方法返回 False。然后,它将值 15 输入到 C1 中。因为这个值符合数据验证规则,cell.getValidationValue() 方法返回 True。类似地,对值 30 返回 False

用Java代码验证单元格值是否符合数据验证规则

// 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