Search code examples
c#epplus

How do I apply Excel data validation for text length to a column with EPPlus?


I am using EPPlus with C# to create an excel file.

I want to put a data validation on a column to not except string longer than certain characters in its cells. Find the attached picture to better understand, what I mean.

Screen shot of the validation dialogue box

I can't find how to give the limitation. If someone has the solution or link to their valid documentaton. Please post it.


Solution

  • This works for me:

    var minLength = 1;
    var maxLength = 4;
    var textValidation = worksheet
        .DataValidations.AddTextLengthValidation("D:D");
    textValidation.ShowErrorMessage = true;
    textValidation.ErrorStyle = ExcelDataValidationWarningStyle.warning;
    textValidation.ErrorTitle = "The value you entered is not valid";
    textValidation.Error = string.Format(
        "This cell must be between {0} and {1} characters in length.",
        minLength, maxLength
    );
    textValidation.Formula.Value = minLength;
    textValidation.Formula2.Value = maxLength;