验证单元格值是否满足数据验证规则
Microsoft Excel 允许用户向单元格添加数据验证规则。例如,十进制验证指定只能输入介于 10 和 20 之间的数字。如果用户输入不同的数字,则 Microsoft Excel 显示一个错误消息,并提示其输入正确范围的数字。如果您复制并粘贴一个数字,比如 3,到该单元格,Excel 不会运行验证检查或显示错误消息。
有时,有必要以编程方式验证一个值是否满足应用于该单元格的数据验证规则。例如,上面的情况下,输入应该是失败的。
介绍
Aspose.Cells提供了Cell.GetValidationValue()方法,以便以编程方式验证单元格值。如果单元格中的值不满足应用于该单元格的数据验证规则,则返回False,否则返回True。
以下示例代码说明了Cell.GetValidationValue()方法的工作方式。首先,它将值3输入到C1。因为这不满足数据验证规则,Cell.GetValidationValue()方法返回False。然后,它将值15输入到C1。因为这个值满足数据验证规则,Cell.GetValidationValue()方法返回True。类似地,对于值30,它返回False。
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET | |
// The path to the documents directory. | |
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); | |
// Instantiate the workbook from sample Excel file | |
Workbook workbook = new Workbook(dataDir+ "sample.xlsx"); | |
// Access the first worksheet | |
Worksheet worksheet = workbook.Worksheets[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.Cells["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 | |
Console.WriteLine("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 | |
Console.WriteLine("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 | |
Console.WriteLine("Is 30 a Valid Value for this Cell: " + cell.GetValidationValue()); |
输出
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