You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

哪个.NET项目可基于Excel数据验证约束程序化验证单元格值?

在NPOI中验证单元格数据规则的现成方案
  • 设置单元格值:直接调用Cell.SetCellValue()的对应重载即可,支持字符串、数字、日期等多种数据类型。
  • 验证单元格值是否符合数据规则:NPOI内置了数据验证的校验逻辑,无需自行编写完整规则,以下是类似公式重算风格的现成实现:
let validateCellValue (cell: ICell) =
    let sheet = cell.Sheet
    // 获取当前工作表的所有数据验证规则
    let dvList = sheet.GetDataValidationHelper().GetValidations()
    // 匹配单元格所在区域的目标验证规则
    let targetDv = dvList |> Seq.tryFind (fun dv ->
        dv.Regions |> Seq.exists (fun reg ->
            reg.FirstRow <= cell.RowIndex && reg.LastRow >= cell.RowIndex &&
            reg.FirstColumn <= cell.ColumnIndex && reg.LastColumn >= cell.ColumnIndex
        )
    )
    match targetDv with
    | Some dv ->
        let constraint = dv.ValidationConstraint
        // 根据验证类型调用内置校验方法
        let isValid = 
            match constraint.ValidationType with
            | ValidationType.WholeNumber ->
                constraint.Validate(cell.NumericCellValue, cell.RowIndex, cell.ColumnIndex)
            | ValidationType.Decimal ->
                constraint.Validate(cell.NumericCellValue, cell.RowIndex, cell.ColumnIndex)
            | ValidationType.List ->
                constraint.Validate(cell.StringCellValue, cell.RowIndex, cell.ColumnIndex)
            | ValidationType.TextLength ->
                constraint.Validate(cell.StringCellValue.Length, cell.RowIndex, cell.ColumnIndex)
            | ValidationType.Date ->
                constraint.Validate(cell.DateCellValue.ToOADate(), cell.RowIndex, cell.ColumnIndex)
            | ValidationType.Time ->
                constraint.Validate(cell.DateCellValue.ToOADate(), cell.RowIndex, cell.ColumnIndex)
            | _ -> true // 未覆盖的类型默认视为有效,可按需扩展
        isValid
    | None -> true // 单元格无对应验证规则时默认有效

说明

该函数会自动定位单元格所属区域的DataValidation规则,通过NPOI原生的ValidationConstraint.Validate()方法完成校验,和公式重算的EvaluateAll()一样,属于框架提供的现成能力,无需手动解析数据验证的规则细节。

内容的提问来源于stack exchange,提问作者toraritte

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 15:36:16