NPOI导出Excel添加单元格验证:下拉框,数字

需求描述:数据导出到Excel,新增对单元格的数据校验。

如图:

1、设置验证,首先要选择单元格的范围

CellRangeAddressList cellRegions = new CellRangeAddressList(1, 65535, 1, 1);

  范围表示:选择第2行到第65535行,第二列

2、创建约束constraint

XSSFDataValidationHelper helper = new XSSFDataValidationHelper((XSSFSheet)sheet);
//创建约束
var dropDownConstraint = helper.CreateExplicitListConstraint(column.DropdownValidation);
//创建验证规则
IDataValidation dropDownValidation = helper.CreateValidation(dropDownConstraint, cellRegions); //column.DropdownValidation是一个数组new string[]{"男","女"}
//设置约束提示信息
dropDownValidation.CreateErrorBox("错误", "请按右侧下拉箭头选择!");
dropDownValidation.ShowErrorBox = true;
sheet.AddValidationData(dropDownValidation);

具体代码供参考:

    CellRangeAddressList cellRegions = new CellRangeAddressList(1, 65535, columnIndex, columnIndex);
    XSSFDataValidationHelper helper = new XSSFDataValidationHelper((XSSFSheet)sheet);
    //启用下拉验证
    if (column.DropdownValidation != null && column.DropdownValidation.Length > 0)
    {
      var dropDownConstraint = helper.CreateExplicitListConstraint(column.DropdownValidation);
      IDataValidation dropDownValidation = helper.CreateValidation(dropDownConstraint, cellRegions);
      dropDownValidation.CreateErrorBox("错误", "请按右侧下拉箭头选择!");
      dropDownValidation.ShowErrorBox = true;
      sheet.AddValidationData(dropDownValidation);
    }
    //启用数字验证
    if (column.NumberValidation)
    {
        var numberValidStart = column.NumberValidStart;
        var numberValidEnd = column.NumberValidEnd;
        var numberConstraint = helper.CreateNumericConstraint(ValidationType.INTEGER, OperatorType.BETWEEN, numberValidStart.ToString(), numberValidEnd.ToString());
        IDataValidation numberValidation = helper.CreateValidation(numberConstraint, cellRegions);
        numberValidation.CreateErrorBox("错误", $"只能输入数字:{numberValidStart}-{numberValidEnd}");
        numberValidation.ShowErrorBox = true;
        sheet.AddValidationData(numberValidation);
    }

 

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/q646926099/article/details/81093853
个人分类: C#
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭