[转]用NPOI操作EXCEL--数据有效性

本文转自:http://www.cnblogs.com/atao/archive/2009/09/22/1572170.html

在有些情况下(比如Excel引入),我们可能不允许用户在Excel随意输入一些无效数据,这时就要在模板中加一些数据有效性的验证。在Excel中,设置数据有效性的方步骤如下: (1)先选定一个区域; (2)在菜单“数据数据有效性”中设置数据有效性验证(如图)。
同样,利用NPOI,用代码也可以实现:

复制代码
HSSFSheet sheet1 = hssfworkbook.CreateSheet("Sheet1");
sheet1.CreateRow(0).CreateCell(0).SetCellValue("日期列"); CellRangeAddressList regions1 = new CellRangeAddressList(16553500); DVConstraint constraint1 = DVConstraint.CreateDateConstraint(DVConstraint.OperatorType.BETWEEN, "1900-01-01""2999-12-31""yyyy-MM-dd"); HSSFDataValidation dataValidate1 = new HSSFDataValidation(regions1, constraint1); dataValidate1.CreateErrorBox("error""You must input a date."); sheet1.AddValidationData(dataValidate1);
复制代码

上面是一个在第一列要求输入1900-1-1至2999-12-31之间日期的有效性验证的例子,生成的Excel效果如下,当输入非法时将给出警告:
下面对刚才用到的几个方法加以说明:       CellRangeAddressList类表示一个区域,构造函数中的四个参数分别表示起始行序号,终止行序号,起始列序号,终止列序号。所以第一列所在区域就表示为:

//所有序号都从零算起,第一行标题行除外,所以第一个参数是1,65535是一个Sheet的最大行数 new CellRangeAddressList(16553500);

      另外,CreateDateConstraint的第一个参数除了设置成DVConstraint.OperatorType.BETWEEN外,还可以设置成如下一些值,大家可以自己一个个去试看看效果:

      最后,dataValidate1.CreateErrorBox(title,text),用来创建出错时的提示信息。第一个参数表示提示框的标题,第二个参数表示提示框的内容。

理解了上面这些,创建一个整数类型的有效性验证也不难实现:

复制代码
sheet1.CreateRow(0).CreateCell(1).SetCellValue("数值列"); CellRangeAddressList regions2 = new CellRangeAddressList(16553511); DVConstraint constraint2 = DVConstraint.CreateNumericConstraint(DVConstraint.ValidationType.INTEGER,DVConstraint.OperatorType.BETWEEN, "0""100"); HSSFDataValidation dataValidate2 = new HSSFDataValidation(regions2, constraint2); dataValidate2.CreateErrorBox("error""You must input a numeric between 0 and 100."); sheet1.AddValidationData(dataValidate2);
复制代码

生成的Excel效果为:
下一节我们将学习利用数据有效性创建下拉列表的例子。

返回目录

原文地址:https://www.cnblogs.com/freeliver54/p/5069341.html