2.6.7 用NPOI操作EXCEL--資料有效性

來源:互聯網
上載者:User
      在有些情況下(比如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效果為:

下一節我們將學習利用資料有效性建立下拉式清單的例子。

 

返回目錄

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.