Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

A built-in way to validate a cell value based on Excel data validation constraints? #1231

Open
tonyqus opened this issue Dec 3, 2023 Discussed in #1217 · 1 comment
Open

Comments

@tonyqus
Copy link
Member

tonyqus commented Dec 3, 2023

Discussed in #1217

Originally posted by toraritte November 21, 2023
What I would like to do:

  1. Set cell value.
  2. Check if the cell value conforms to the data validation rules referencing that cell.

I could extract all the information needed to create a validation function, but don't want to re-invent the wheel. I didn't find the NPOI docs yet (is it the source?), and based on my experiments, there is no such function, but perhaps I was looking in the wrong places.

Apache POI's XSSFDataValidationConstraint class does have a validate method, but the docs are not much help and I don't know Java:

validate
public void validate()


edit: Just found Apache POI's DataValidationEvaluator class and I presume that NPOI.SS.Formula.DataValidationEvaluator is the corresponding NPOI class. Am I on the right track?

@toraritte
Copy link

These are the challenges I've found, and this is how Apache POI does it:

1.2.3 How to evaluate Excel formulas / functions?

As mentioned above, built-in Excel functions are not part of the Open XML SDK and so one would have to re-implement them in the framework itself. At least, this is how Apache POI's [DataValidationEvaluator][2] (source) works: after jumping through a bunch of hoops2, eventually FormulaParser.parse (source) will get called, and the validation evaluator will apply the subset of Excel functions implemented in Java or throw an error.

[2]: DataValidationEvaluator [ isValidCell -> isValid -> isValidValue -> getValidationValuesForConstraint]
-> WorkbookEvaluator [ evaluateList -> evaluate ]
-> FormulaParser [ parse ]

The same applies to custom VBA scripts as well. They can be set using Open XML SDK, but that's it.

NPOI has a way to re-calculate formulas, (F# again, sorry)

let recalculateFormulas (workbook: XSSFWorkbook) =
    let creationHelper = workbook.GetCreationHelper()
    let formulaEvaluator = creationHelper.CreateFormulaEvaluator()
    formulaEvaluator.EvaluateAll()

but this will only evaluate formula-type cells, and not the formulas embedded into data validations (see IDataValidationConstraint).

@tonyqus tonyqus modified the milestones: NPOI 2.7.1, NPOI 2.7.2 May 9, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants