EPPlus的Validate方法如何工作?

时间:2017-04-01 16:06:52

标签: epplus

我使用EPPlus作为计算服务器。这是我的代码:

using (var xlp = new ExcelPackage(stream))
{
OfficeOpenXml.ExcelWorksheet Sheet = xlp.Workbook.Worksheets["sheet1"];
//Some code for feeding user data to excel sheet
//...

//We first invoke calculate method to let contraints of data validation get updated.
xlp.Workbook.Calculate();   

var v = Sheet.DataValidations["A1"];
if (v != null)
{
    switch (v.ValidationType.Type)
    {
        case OfficeOpenXml.DataValidation.eDataValidationType.DateTime:     
            OfficeOpenXml.DataValidation.ExcelDataValidationDateTime V1 = (OfficeOpenXml.DataValidation.ExcelDataValidationDateTime)v;
            try
            {
                //this line doesn't do any thing
                V1.Validate();
            }
            catch
            {
            }           
        break;
        case ...
    }
}
}

我曾在某处读过Validate()方法抛出无效数据的异常。它没有。 我的问题:如何使用Validate()方法?

1 个答案:

答案 0 :(得分:1)

这将取决于单元格的内容和验证器操作员的设置:

http://epplus.codeplex.com/SourceControl/latest#EPPlus/DataValidation/ExcelDataValidationOperator.cs

/// <summary>
/// Operator for comparison between Formula and Formula2 in a validation.
/// </summary>
public enum ExcelDataValidationOperator
{
    any,
    equal,
    notEqual,
    lessThan,
    lessThanOrEqual,
    greaterThan,
    greaterThanOrEqual,
    between,
    notBetween
}

ExcelDataValidationDateTime(最终)派生自ExcelDataValidationWithFormula<IExcelDataValidationFormulaDateTime>,其中包含Validate()的实现:

http://epplus.codeplex.com/SourceControl/latest#EPPlus/DataValidation/ExcelDataValidationWithFormula.cs

public override void Validate()
{
    base.Validate();
    if (Operator == ExcelDataValidationOperator.between || Operator == ExcelDataValidationOperator.notBetween)
    {
        if (string.IsNullOrEmpty(Formula2Internal))
        {
            throw new InvalidOperationException("Validation of " + Address.Address + " failed: Formula2 must be set if operator is 'between' or 'notBetween'");
        }
    }
}

因此,当验证操作为ExcelDataValidationOperator.betweenExcelDataValidationOperator.notBetween且未设置Forumla2时,它将抛出异常(invalidate)(不要与主{{1}混淆})。换句话说,当您使用需要两个值/公式进行比较但只设置了一个的操作时,它认为验证器无效。