在有些情況下(比如Excel引入),我們可能不允許使用者在Excel隨意輸入一些無效資料,這時就要在模板中加一些資料有效性的驗證。在Excel中,設定資料有效性的方步驟如下:
(1)先選定一個地區;
(2)在菜單“資料資料有效性”中設定資料有效性驗證()。
同樣,利用NPOI,用代碼也可以實現:HSSFSheet sheet1 = hssfworkbook.CreateSheet("Sheet1");
sheet1.CreateRow(0).CreateCell(0).SetCellValue("日期列");
CellRangeAddressList regions1 = new CellRangeAddressList(1, 65535, 0, 0);
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(1, 65535, 0, 0);
另外,CreateDateConstraint的第一個參數除了設定成DVConstraint.OperatorType.BETWEEN外,還可以設定成如下一些值,大家可以自己一個個去試看看效果:
最後,dataValidate1.CreateErrorBox(title,text),用來建立出錯時的提示資訊。第一個參數表示提示框的標題,第二個參數表示提示框的內容。
理解了上面這些,建立一個整數類型的有效性驗證也不難實現:
sheet1.CreateRow(0).CreateCell(1).SetCellValue("數值列");
CellRangeAddressList regions2 = new CellRangeAddressList(1, 65535, 1, 1);
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效果為:
下一節我們將學習利用資料有效性建立下拉式清單的例子。
返回目錄